javascript - mongodb JavaScript : return document with only matched sub-document

标签 javascript mongodb

有人知道如何在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/

相关文章:

mongodb - 使用 mongodb 建立索引 : bad performance/indexOnly=false

mongodb - 无法通过 mongo 的官方 node.js 驱动程序进行身份验证,只能通过 mongo shell 进行身份验证。 (MongoDB Cloud Manager 副本部署)

javascript - 将特定客户端逻辑应用于一组相关元素的最佳方法

javascript - 185.3 + 12.37 = 197.67000000000002?

javascript - jQuery 使用 'this' 添加/删除类

c# - 防止变量丢失

javascript - 过度使用 jQuery 的 preventDefault() 和 stopPropagation()

node.js - mongoose findById 在我使用字符串文字时有效,但在引用对象的属性时无效

javascript - 每第二次运行都会抛出 : MongoError: Topology was destroyed

node.js - 如何只更新一次 MongoDB 文档字段?