有人知道如何在javascript中返回仅包含匹配子文档的文档吗?
例如这是数据库记录:
[
{"name":"bestbuy",notes:["article IT", "article 2"]},
{"name":"microsoft",notes:["article IT", "another IT", "article 5"]},
{"name":"IBM",notes:["article 8", "article 9"]}
]
这是我的查询:
collection.find({"company.notes":/IT/}, function(err,result){})
结果是:
[
{"name":"bestbuy",notes:["article IT", "article 2"]},
{"name":"microsoft",notes:["article IT", "another IT", "article 5"]},
]
但我的预期结果是:
[
{"name":"bestbuy",notes:["article IT"]},
{"name":"microsoft",notes:["article IT", "another IT"]}
]
有什么想法吗? 谢谢
最佳答案
您可以使用聚合
db.collection.aggregate([
{$match: {"notes": /IT/}},
{$unwind: "$notes"},
{$match: {notes: /IT/}},
{$group: {_id: '$_id', name: {$first: '$name'}, notes: {$push: '$notes'}}},
{$project: {'name': 1, 'notes': 1, _id: 0}}
])
产量:
{ "name" : "microsoft", "notes" : [ "article IT", "another IT" ] }
{ "name" : "bestbuy", "notes" : [ "article IT" ] }
关于javascript - mongodb JavaScript : return document with only matched sub-document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31891038/