fadeltd
fadeltd

Reputation: 349

add array to existing nested array without duplicates mongodb

This is my User Collection

{ _id: ObjectId("589803bf53860d4a3475afa3"),
  "username": "fadeltd",
  "gender": "Male",
  "updatedAt": ISODate("2017-02-06T05:03:59.969Z"),
  "createdAt": ISODate("2017-02-06T05:03:59.969Z"),
  "shoppingList": [{
      "title": "Personal List",
      "ingredients": ["5 Eggs"]
  }]
})

What I'm trying to do is to push data to my shopping list, with $addToSet so that there will be no duplicate shopping list data

This is my script

User.update({ 
        _id: ObjectId("589803bf53860d4a3475afa3"), 
        'shoppingList.title': "Personal List"
    }, 
    {
        $addToSet: {
            "shoppingList.$.ingredients": ["5 Eggs", "3 Milks"]
        }
    })

But when I try that script I get this

{ _id: ObjectId("589803bf53860d4a3475afa3"),
  "username": "fadeltd",
  "gender": "Male",
  "updatedAt": ISODate("2017-02-06T05:03:59.969Z"),
  "createdAt": ISODate("2017-02-06T05:03:59.969Z"),
  "shoppingList": [{
      "title": "Personal List",
      "ingredients": ["5 Eggs", ["5 Eggs", "3 Milks"]],
  }]
})

I want the ingredients to be ["5 Eggs", "3 Milks"] instead of nested array ["5 Eggs", ["5 Eggs", "3 Milks"]]

Upvotes: 1

Views: 156

Answers (1)

chridam
chridam

Reputation: 103435

Use the $each modifier which allows you to add multiple values to an array

User.update(
    { 
        "_id": ObjectId("589803bf53860d4a3475afa3"), 
        "shoppingList.title": "Personal List"
    }, 
    {
        "$addToSet": {
            "shoppingList.$.ingredients": { 
                "$each": ["5 Eggs", "3 Milks"] 
            }
        }
    }
)

Upvotes: 1

Related Questions