MongoDB:在没有$ unwind的嵌入式文档数组中进行字段比较?

时间:2019-01-18 12:27:42

标签: mongodb mongodb-query aggregation-framework

假设我有一个文档,其中包含一系列具有相同结构的嵌入式文档:

{
    "_id": ObjectId('5c41c2a3c3238118a0950a7b'),
    "subdocuments": [
        {
            "_id": ObjectId('5c41c2b4c3238118a0950a7c'),
            "field1: "A",
            "field2: "A"
        },
        {
            "_id": ObjectId('5c41c2b6c3238118a0950a7d'),
            "field1: "B",
            "field2: "C"
        }
    ]
}

我想在同一子文档中比较field1field2,并将结果投影到该子文档中,即:

{
    "_id": ObjectId('5c41c2a3c3238118a0950a7b'),
    "subdocuments": [
        {
            "_id": ObjectId('5c41c2b4c3238118a0950a7c'),
            "field1: "A",
            "field2: "A",
            "fields_equal": true
        },
        {
            "_id": ObjectId('5c41c2b6c3238118a0950a7d'),
            "field1: "B",
            "field2: "C",
            "fields_equal": false
        }
    ]
}

我想这样做而无需放松subdocuments。这不起作用:

'$addFields': {
    'subdocuments.fields_equal': {
        '$eq': ['$subdocuments.field1','$subdocuments.field2']
    }
}

有关如何操作的任何想法?甚至有可能吗?

2 个答案:

答案 0 :(得分:1)

运行此聚合。

db.collection.aggregate([{
  '$addFields': {
    'subdocuments': {
      $map: {
        input: "$subdocuments",
        in: {
          $mergeObjects: [{
              fields_equal: { $eq: ["$$this.field1", "$$this.field2"] }
            },
            "$$this"
          ]
        }
      }
    }
  }
}])

答案 1 :(得分:0)

db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$subdocuments",

            }
        },

        // Stage 2
        {
            $addFields: {
                "subdocuments.fields_equal": {
                    $cond: {
                        if: {
                            $eq: ["$subdocuments.field1", "$subdocuments.field2"]
                        },
                        then: true,
                        else: false
                    }
                }
            }
        },

        // Stage 3
        {
            $group: {
                _id: '$_id',
                subdocuments: {
                    $addToSet: '$subdocuments'
                }
            }
        },

    ]



);