当前位置: 代码迷 >> JavaScript >> mongodb javascript:返回仅包含匹配子文档的文档
  详细解决方案

mongodb javascript:返回仅包含匹配子文档的文档

热度:160   发布时间:2023-06-07 15:29:00.0

有谁知道如何用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" ] }
  相关解决方案