【问题标题】:Mongodb aggregate push indexMongoDB聚合推送索引
【发布时间】:2019-07-22 11:04:55
【问题描述】:

我有以下文件:

  {
    _id: "1",
    firstName: "john",
    lastName: "Doe",
    cars: [
      {
        "_id": "2",
        "carName": "BMW",
        "carModel": "330",
        "carColor": "silver"
      },
      {
        "_id": "4",
        "carName": "BMW",
        "carModel": "330",
        "carColor": "pink"
      },
      {
        "_id": "5",
        "carName": "Lexus",
        "carModel": "IS300",
        "carColor": "white"
      },
      {
        "_id": "6",
        "carName": "LADA",
        "carModel": "2106",
        "carColor": "blue"
      }
    ]
  }

使用聚合查询,我从以下文档的 cars 数组返回特定​​对象:

db.collection.aggregate([
  {
    $match: {
      firstName: "john"
    }
  },
  {
    $unwind: "$cars"
  },
  {
    $match: {
      "cars.carName": {
        "$in": [
          "Lexus",
          "LADA"
        ]
      }
    }
  },
  {
    $group: {
      "_id": null,
      cars: {
        $push: "$cars"
      }
    }
  }
])

是否也可以获取推送到cars 数组的每个对象的索引?

例如:

[
  {
    "_id": null,
    "cars": [
      {
        "_id": "5",
        "carColor": "white",
        "carModel": "IS300",
        "carName": "Lexus",
        "index": 2
      },
      {
        "_id": "6",
        "carColor": "blue",
        "carModel": "2106",
        "carName": "LADA",
        "index": 4
      }
    ]
  }
]

可以测试聚合查询here

【问题讨论】:

    标签: arrays database mongodb mongoose mongodb-query


    【解决方案1】:

    您可以尝试以下聚合 (includeArrayIndex)

    db.collection.aggregate([
      { "$match": { "firstName": "john" }},
      { "$unwind": { "path": "$cars", "includeArrayIndex": "index", }},
      { "$match": { "cars.carName": { "$in": ["Lexus", "LADA"] }}},
      { "$addFields": { "cars.index": "$index" }},
      { "$group": {
        "_id": null,
        "cars": { "$push": "$cars" }
      }}
    ])
    

    Mongoplayground

    【讨论】:

    • 是否有其他方法可以在不使用$mergeObjects 的情况下实现这一目标?我有 3.2 版本的 mongoDb,它不支持该属性。
    • 我*更新了我的答案
    • 非常感谢。这个答案对我帮助很大!我被这个索引问题困了几个小时。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-26
    • 2022-11-22
    • 1970-01-01
    • 2013-11-04
    • 2019-05-26
    相关资源
    最近更新 更多