0

这是我正在使用的数据的架构:

{
    _id: ObjectId(),
    field1 : {
        subField1: String,
        subField2: String
    },
    field2 : {
        subField1: String,
        subField2: String
    }
}

我想检查 field1.subField1 或 field2.subField1 是否等于某个值,然后相应地检索其他字段。例如,如果 field1.subField1 等于我要搜索的值,那么我想获取 field2 的值,反之亦然。我尝试使用$elemMatch但无法找出正确的解决方案。谢谢你。

4

2 回答 2

1

这是另一种方法,也许比我的其他答案更直接......

再次假设以下文档,并且您希望找到 field1 是“CCC”的位置...

{
    _id: ObjectId(),
    field1 : {
        subField1: "AAA",
        subField2: "BBB"
    },
    field2 : {
        subField1: "CCC",
        subField2: "DDD"
    }
}

...这是聚合...

db.mycollection.aggregate([
    {
        $project:
        {
            desiredValue:
            {
                $switch:
                {
                    branches:
                    [
                        {
                            case: { $eq: [ "$field1.subField1", "CCC" ] },
                            then: "$field1.subField2"
                        },
                        {
                            case: { $eq: [ "$field2.subField1", "CCC" ] },
                            then: "$field2.subField2"
                        }
                    ],
                    default: null
                }
            }
        }
    }
])

这是一个单阶段聚合,带有一个比较字段并选择输出的 switch 语句。

于 2021-06-13T18:56:15.143 回答
0
db.mycollection.aggregate([
    {
        $group:
        {
            _id: "$_id",
            array1: { $push: "$field1" },
            array2: { $push: "$field2" },
        }
    },
    {
        $project:
        {
            _id: 1,
            arrayConcat: { $concatArrays: [ "$array1", "$array2" ] }
        }
    },
    {
        $unwind: "$arrayConcat"
    },
    {
        $match: { "arrayConcat.subField1": "CCC" }
    },
    {
        $project: { desiredValue: "$arrayConcat.subField2"}
    }
])

解释:

假设以下文件...

{
    _id: ObjectId(),
    field1 : {
        subField1: "AAA",
        subField2: "BBB"
    },
    field2 : {
        subField1: "CCC",
        subField2: "DDD"
    }
}

...并假设您希望从键“CCC”中找到值“DDD”...

  1. 对集合执行聚合。
  2. 按 _id 分组,以便每条记录隔离数据。此分组将使用 $push 将对象“field1”和“field2”转换为数组。
  3. 使用 $project 将两个数组连接在一起,使它们共享同一个数组对象。
  4. 展开数组对象,使字段现在位于相同位置,但每个文档分开。
  5. 匹配所需的查询字段值 - 示例显示“CCC”。投影所需的输出字段 - 示例显示字段名称“desiredValue”。

笔记:

如果您一开始就使用属性模式,这会更容易。请参阅https://www.mongodb.com/blog/post/building-with-patterns-the-attribute-pattern

于 2021-06-13T18:36:59.810 回答