【问题标题】:mongodb javascript: return document with only matched sub-documentmongodb javascript:返回仅包含匹配子文档的文档
【发布时间】:2015-10-31 16:25:02
【问题描述】:

有人知道如何在 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"]}
]

有什么想法吗? 谢谢

【问题讨论】:

标签: javascript mongodb


【解决方案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" ] }

【讨论】:

  • 谢谢,我没有尝试,因为我发现数据库架构不同,所以我更新了我的问题。你能解释一下吗?
  • 还有一个问题:为什么需要使用2个"$match"s?
  • @aaron 这是第一个问题的答案。如果您的数据库架构不同,请接受答案并提出一个新问题。您不应创建chameleon 问题。
  • 然后我试了,代码抛出,头疼。。输出为:collection opens D:\Test\node_modules\mongodb\lib\mongodb\connection\base.js:246 throw message; ^ TypeError: object is not a function at D:\Test\node_modules\mongodb\lib\mongodb\collection\aggregation.js:317:7
  • var results = collection.aggregate([ {$match: {"notes": /IT/}}, {$unwind: "$notes"}, {$match: {notes: /IT /}},{$group:{_id:'$_id',名称:{$first:'$name'},注释:{$push:'$notes'}}},{$project:{'name' : 1, 'notes': 1, _id: 0}}]);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-01-16
  • 2018-06-13
  • 2021-01-01
  • 2021-02-25
  • 2021-08-06
  • 2015-06-09
  • 1970-01-01
相关资源
最近更新 更多