【问题标题】:How to find documents and use aggregate to find a property in mongodb?如何查找文档并使用聚合在 mongodb 中查找属性?
【发布时间】:2020-07-10 09:47:02
【问题描述】:

我在一个集合中有数千个文档。下面是一个示例文档

{
  _id: 12345,
  createdDate: "2020-07-10",
  cars: [
    {
      type: "Sedan",
      engine: [
        {
          type: "Petrol",
          power: 150,
          brake: {
            type: "Disc",
            hasABS: false
          }
        },
        {
          type: "Petrol",
          power: 190,
          brake: {
            type: "Drum",
            hasABS: false
          }
        },
        {
          type: "Diesel",
          power: 160,
          brake: {
            type: "Disc",
            hasABS: true
          }
        }
      ]
    },
    {
      type: "SUV",
      engine: [
        {
          type: "Petrol",
          power: 150,
          brake: {
            type: "Disc",
            hasABS: false
          }
        },
        {
          type: "Petrol",
          power: 190,
          brake: {
            type: "Drum",
            hasABS: false
          }
        },
        {
          type: "Diesel",
          power: 160,
          brake: {
            type: "Disc",
            hasABS: true
          }
        }
      ]
    }
  ]
}

现在我想查找在 7 月份创建的汽车并聚合以查找带有 abs 刹车的汽车

以下是我的查询:

db.getCollection('collection')
    .find({
        $and: [
            {"createdDate": {"$gte": new Date("2020-07-01"), "$lt": new Date("2020-07-10")}},
            aggregate(
                {"$unwind": "$cars"},
                {"$unwind": "$cars.engine"},
                {"$match": {"cars.engine.brake.hasABS": true}},
                {"$project": {"cars": 1}},
                {"$group": {"_id": "$cars"}}
            )
        ]
    })
    .pretty()

当我尝试运行上述查询时,出现错误。这是应该这样做还是有更好的方法?

【问题讨论】:

    标签: arrays mongodb mongodb-query nosql mongo-collection


    【解决方案1】:

    您不能同时使用.find().aggreate()。在这种情况下,您可以在 $match 聚合阶段使用相同的过滤器:

    db.collection.aggregate([
        { $match: { createdDate: { $gte: "2020-07-01", $lt: "2020-07-10" } } }, // or { "$gte" : new Date("2020-07-01"), "$lte" : new Date("2020-07-10") }
        { "$unwind": "$cars" },
        { "$unwind": "$cars.engine"},
        { "$match": {"cars.engine.brake.hasABS" : true}}
    ])
    

    Mongo Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-26
      • 2016-08-29
      • 1970-01-01
      • 1970-01-01
      • 2019-01-17
      • 2017-05-05
      • 1970-01-01
      • 2022-07-22
      相关资源
      最近更新 更多