[英]mongodb javascript: return document with only matched sub-document
anyone know how to return the document with only matched sub-document in javascript? 有谁知道如何用javascript中仅匹配的子文档返回文档?
eg here is the database records: 例如,这是数据库记录:
[
{"name":"bestbuy",notes:["article IT", "article 2"]},
{"name":"microsoft",notes:["article IT", "another IT", "article 5"]},
{"name":"IBM",notes:["article 8", "article 9"]}
]
here is my query: 这是我的查询:
collection.find({"company.notes":/IT/}, function(err,result){})
result is: 结果是:
[
{"name":"bestbuy",notes:["article IT", "article 2"]},
{"name":"microsoft",notes:["article IT", "another IT", "article 5"]},
]
but my expected result is: 但我的预期结果是:
[
{"name":"bestbuy",notes:["article IT"]},
{"name":"microsoft",notes:["article IT", "another IT"]}
]
any idea? 任何想法? thanks
谢谢
You can use aggregation 您可以使用聚合
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}}
])
yields: 产量:
{ "name" : "microsoft", "notes" : [ "article IT", "another IT" ] }
{ "name" : "bestbuy", "notes" : [ "article IT" ] }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.