Babak Abadkheir
Babak Abadkheir

Reputation: 2350

mongodb $addToSet _ adding object is not working properly _ mongoose

according to mongoDB documentation about $addToSet operator:

$addToSet only ensures that there are no duplicate items added to the set and does not affect existing duplicate elements. $addToSet does not guarantee a particular ordering of elements in the modified set.

so my problem is :

I have an array field that contains objects.

foo = [ {a:1, b:2}, {a:3, b:2}]

so when I try to push objects in it, the behavior is not working properly :

db.myCollection.updateOne({"some_id"}, {$addToSet:{foo:{a:1, b:2}}})

the result would be :

foo = [ {a:1, b:2}, {a:3, b:2}, {a:1, b:2}]

validation on duplicate objects not working. why?

Upvotes: 1

Views: 1403

Answers (1)

Gibbs
Gibbs

Reputation: 22956

@Gibbs v3.6.8 . this is my query : MyCollection.findOneAndUpdate({ package_name: req.body.package_name, }, { $addToSet: { foo: {a:2, b: 3}, } }, { upsert: true, multi: true, new: true })

Because mongo considers 2 and 3 as Double by default. Hence 2.0 is not same as 2. So it inserts.

//NumberInt solves the issue

To avoid this,

db.getCollection('test').findOneAndUpdate({
  _id: ObjectId("5f0d7ab89e001b53e3995a5b")
},
{
  $addToSet: {
    foo: {
      a: NumberInt(2),
      b: NumberInt(3)
    }
  }
},
{
  upsert: true,
  multi: true,
  new: true
})

Upvotes: 1

Related Questions