【问题标题】:Finding only an item in an array of arrays by value with Mongoose使用 Mongoose 仅​​按值查找数组数组中的一项
【发布时间】:2017-06-27 13:29:30
【问题描述】:

这是我的架构示例,其中包含一些数据:

client {
  menus: [{
    sections: [{
      items: [{
        slug: 'some-thing'
      }]
    }]
  }]
}

我正在尝试像这样选择它:

Schema.findOne({ client._id: id, 'menus.sections.items.slug': 'some-thing' }).select('menus.sections.items.$').exec(function(error, docs){
  console.log(docs.menus[0].sections[0].items[0].slug);
});

当然,“docs.menus[0].sections[0].items[0].slug”只有在每个数组中只有一个东西的情况下才有效。如果每个数组中有多个项目,而无需遍历所有内容来找到它,我该如何完成这项工作?

如果您需要更多详细信息,请告诉我。

【问题讨论】:

  • 您的问题实际上是多个menus.sections.items.slug 可以匹配“某事”并且您想返回所有这些,而不仅仅是一个。还是你的意思是别的?
  • 不,slug 是唯一的,应该只返回一件事,但它返回父数组中的所有内容......所以使用 [0] 不起作用。
  • 我的问题写得不好。像 Schema.findOne({ client._id: id, 'menus._id': id }).select('menus.$') ... 会返回一个包含一项的数组,即。 docs.menus[0] ...当您比单个数组(数组中的数组)更深时,有没有办法做到这一点?
  • 基本上,我只希望它返回相关的菜单、部分、项目...而不是所有菜单、部分等。

标签: node.js mongodb mongoose mongodb-query aggregation-framework


【解决方案1】:

aggregation framework 非常适合在深度嵌套的数组中查找位置运算符会使您失败的内容:

Model.aggregate(
    [
       // Match the "documents" that meet your criteria
       { "$match": {
           "menus.sections.items.slug": "some-thing"
       }},

       // Unwind the arrays to de-normalize as documents
       { "$unwind": "$menus" },
       { "$unwind": "$menus.sections" },
       { "$unwind": "$menus.sections.items" }


       // Match only the element(s) that meet the criteria
       { "$match": {
           "menus.sections.items.slug": "some-thing"
       }}

       // Optionally group everything back to the nested array
       // One step at a time
       { "$group": {
           "_id": "$_id",
           "items": { "$push": "$menus.sections.items.slug" }
       }},
       { "$group": {
           "_id": "$_id",
           "sections": { 
               "$push": { "items": "$items" }
           }
       }},
       { "$group": {
           "_id": "$_id",
           "menus": { 
               "$push": { "sections": "$sections" }
           }
       }},
    ],
    function(err,results) {

    }
)

另请参阅$first 等其他聚合运算符,以便在使用$group 时保留文档中的其他字段。

【讨论】:

    猜你喜欢
    • 2019-05-23
    • 2020-07-08
    • 2014-12-29
    • 2019-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    • 1970-01-01
    相关资源
    最近更新 更多