如何更新或返回子文档

时间:2014-08-24 03:29:35

标签: node.js mongodb

我有这样的文件。

{
    '_id': xxx,
    'name': xxx,
    'background': [],
    'songs': [
        {
            'title': xxx,
            'background': []
        }
    ]
}

首先,我怎么能只返回歌曲文件。我想要这样的东西。

function(err, doc) {
    //the doc is {'title': xxx, 'background': []}
}

其次,我怎样才能推送文档在歌曲中的背景数组中的数据。

collection.update(
    {'_id': xxx, songs: {$elemMatch:{'title': xxx}},
    {
         $push: {'background': xxx}
    }
)

此示例代码始终将数据推送到根文档而不是歌曲文档的背景中。

1 个答案:

答案 0 :(得分:1)

您可以通过projection限制从Mongo查询返回的字段。这可能看起来像

collection.find( { /*some criteria*/ }, { song: 1, _id:0 } )

要修改文档中数组中的元素,您需要使用positional $ operator

collection.update( {'_id': xxx, songs: {$elemMatch:{'title': xxx}}, { $push: {'songs.$.background': xxx} }, callback )