合并Mongo文档中的字段

时间:2018-03-07 14:26:28

标签: mongodb mongodb-query

我有一个名为Cars的mongo集合,其中包含以下格式的文档:

{ "_id": "100066114", "cars": [{ "_id": ObjectId("5a9fed0218071f56ba7eca48"), "customer_name": "ABC", "otherdetails":"some details" }, { "_id": ObjectId("5a9fed0218071f56ba7eca4a"), "customer_name": "", "otherdetails":"some other details" }, { "_id": ObjectId("5a9fed0218071f56ba7eca49"), "customer_name": "", "otherdetails":"some more details" }, { "_id": ObjectId("5a9fed0218071f56ba7eca47"), "customer_name": "ABC", "otherdetails":"details" }] }

我想将此文档更改为以下格式:

{ "_id": "100066114", "customer_name":"ABC" "cars": [{ "_id": ObjectId("5a9fed0218071f56ba7eca48"), "otherdetails":"some details" }, { "_id": ObjectId("5a9fed0218071f56ba7eca4a"), "otherdetails":"some other details" }, { "_id": ObjectId("5a9fed0218071f56ba7eca49"), "otherdetails":"some more details" }, { "_id": ObjectId("5a9fed0218071f56ba7eca47"), "otherdetails":"details" }] }

我如何实现这一目标?

1 个答案:

答案 0 :(得分:0)

我认为应该将customer_name评估为来自汽车的第一个非空值

  db.Cars.aggregate([
  {
    $project: {
      customer_name: {
        $arrayElemAt: [
          { $filter: { input: { $map: { input: "$cars", as: "car", in: "$$car.customer_name" } }, 
            as: "customer_name", cond: {$ne: ["$$customer_name", ""]} } }          
        ,0]
      },
      cars: {
        $map: {
          input: "$cars",
          as: "car",
          in: { _id: "$$car._id", otherdetails: "$$car.details" }
        }
      }
    }
  }
])

因此,要获取cars数组,您只需使用$map指定应将哪些属性传输到输出。要评估customer_name,您应该从每辆车中customer_name(使用$map)过滤掉空字符串(使用$filter)并获取第一项(使用$arrayElemAt