任何人都知道如何使用javascript中匹配的子文档返回文档?
e.g。这是数据库记录:
[
{"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"]}
]
任何想法? 感谢
答案 0 :(得分:1)
您可以使用聚合
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" ] }