【问题标题】:Filtering an embedded array in MongoDB过滤 MongoDB 中的嵌入式数组
【发布时间】:2014-06-30 02:46:39
【问题描述】:

我有一个 Mongodb 文档,其中包含一个深深嵌入文档中的数组。在我的一项操作中,我想返回整个文档,但过滤掉该数组中不符合该条件的元素。

这是一些简化的数据:

{
   id: 123 ,
   vehicles : [
     {name: 'Mercedes', listed: true},
     {name: 'Nissan', listed: false},
     ...
   ]
}

因此,在此示例中,我想要整个文档,但我希望 vehicles 数组仅包含将 listed 属性设置为 true 的对象。

解决方案

理想情况下,我正在寻找使用 mongo 查询的解决方案(例如 `$unwind、$elemMatch 等...),但我也在使用 mongoose,所以使用 Mongoose 的解决方案是可以的。

【问题讨论】:

    标签: arrays mongodb mongoose


    【解决方案1】:

    你可以像这样使用聚合框架:

    db.test312.aggregate(
        {$unwind:"$vehicles"},
        {$match:{"vehicles.name":"Nissan"}},
        {$group:{_id:"$_id",vehicles:{$push:"$vehicles"}}}
    )
    

    【讨论】:

    • 如何在主对象中保留属性? (例如 { id: 123 , name: 'testName', 车辆 : [ ... ] })
    • 通过将字段添加到 {$group:{_id:{_id:"$_id",name:"$name"}}, vehic...} 或使用 {_id:"$ _id",name:{$last:"$name"},vehic..}。在第一种情况下,您需要在 {$group} 之后添加 {$project:{}} 以解开 _id
    • 谢谢,我有点走第二种方式,但第一种似乎更干净
    • 这个方法其实我也遇到过问题: 追问:stackoverflow.com/questions/23636175/…
    【解决方案2】:

    你可以使用$addToSet在组上展开并匹配列出的等于true。

    示例外壳查询:

    db.collection.aggregate([
    {
        $unwind: "$vehicles"
    },
    {
        $match: {
            "vehicles.listed": {
                $eq: true
            }
        }
    },
    {
        $group: {
            _id: "$id",
            vehicles: {
                "$addToSet": {
                    name: "$vehicles.name",
                    listed: "$vehicles.listed"
                }
            }
        }
    },
    {
        $project: {
            _id: 0,
            id: "$_id",
            vehicles: 1
        }
    }
    ]).pretty();
    

    【讨论】:

      猜你喜欢
      • 2020-10-01
      • 2018-08-09
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2022-01-17
      • 2011-01-09
      • 2021-02-17
      • 1970-01-01
      相关资源
      最近更新 更多