mongodb javascript:只返回匹配的子文档的文档

时间:2015-08-08 08:03:37

标签: javascript mongodb

任何人都知道如何使用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"]}
]

任何想法? 感谢

1 个答案:

答案 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" ] }