MongoDB无需使用索引即可embedded到数组中
我正在寻找$push
入一个嵌套的数组,其中父数组匹配一个简单的属性条件:
以下是我的文档的外观:
{ name: "Foo", boardBucket: { currentBoardId: 1234, items: [ <- looking to push into `boardItems` of an `item` in this Array { boardId: 1234, <- that has `boardId: 1234` boardItems: [ "barItem", "deyItem" ] <- Final Array I want to push to } ] } }
所以我想在boardId: 1234
item
boardItems
中推"fooItem"
选项1:我可以使用点符号和索引访问
我当然可以通过使用dot.notation使用项目的索引来执行$push
,如下所示:
this.update({ '$push': {"boardBucket.items.0.boardItems": "fooItem" } });
但是,如果我不知道索引呢?
我怎样才能推入boardItems
boardId: 1234
item
boardId: 1234
而不使用索引(而不是使用boardId
)?
注意:
- 我使用mongoose作为数据库驱动程序
- 我想避免使用mongoose的
save()
因为它往往是越野车+它似乎保留了本地对象的副本,我想避免 - 只是直接
update()
mongo查询是我所追求的 - 我当然希望避免任何types的整个文件抓取执行此更新,因为我的文件是巨大的
(对不起,没有抽样,当时是在急于)
db.myDb.insert({ name: "Foo", boardBucket: { currentBoardId: 1234, items: [ { boardId: 1234, boardItems: [ "barItem", "deyItem" ] }, { boardId: 1235, boardItems: [ "dontPushToThisOne" ] } ] } }); db.myDb.insert({ name: "Foo2", boardBucket: { currentBoardId: 1236, items: [ { boardId: 1236, boardItems: [ "dontPushToThisOne" ] } ] } }); db.myDb.update( { "boardBucket.currentBoardId":1234, "boardBucket.items.boardId":1234}, { "$push" : {"boardBucket.items.$.boardItems":"fooItem"} }, {multi:1} );
我认为这应该做的伎俩:
this.update( {"boardBucket.items": {$elemMatch: { boardId: "1234"}}}, {'$push': {"boardBucket.items.boardItems": "fooItem" }} );