将数组添加到现有嵌套数组而不重复mongodb

时间:2017-02-06 07:23:50

标签: javascript arrays mongodb

这是我的用户收藏

{ _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"]
  }]
})

我要做的是使用$addToSet将数据推送到我的购物清单,这样就不会有重复的购物清单数据

这是我的剧本

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

但是当我尝试这个脚本时,我得到了这个

{ _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"]],
  }]
})

我希望成分为["5 Eggs", "3 Milks"]而不是嵌套数组["5 Eggs", ["5 Eggs", "3 Milks"]]

1 个答案:

答案 0 :(得分:1)

使用 $each 修饰符,它允许您向数组添加多个值

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