Tuesday, 18 April 2017

mongoDB subdocument match where elemMatch is not object

I have a subdocument with a schema like the following

{
    things: [ { thing: { type: String }, otherThing: { type: String } ]
}

Let's pretend it's populated like so

[
    { thing: 'Thing 1', otherThing: '123-001'},
    { thing: 'Thing 2', otherThing: '123-002'},
    { thing: 'Thing 3', otherThing: '123-003'},
    { thing: 'Thing 4', otherThing: '123-004'}
]

I want to now insert into this Thing 5, but I want to check if it exists first, so I do:

Things.findOneAndUpdate(
{ 
  things: {
    $elemMatch: {
      thing: {
        $ne: 'Thing 5'
      }
    }
  }
}, 
{ 
  $push: { 
    things : { 
      thing: 'Thing 5', 
      otherThing: '123-005'
    }
  }
})

When I run the script the first time, Thing 5 gets inserted. When I run it the second time, I expect it to fail, but it inserts a duplicate "Thing 5".

I suspect this is because $elemMatch thing $ne matches Thing 1 - 4 and therefore will push. What do I need to do so it basically says "if Thing 5 isn't inside any of these subdocuments"?



via BpH

No comments:

Post a Comment