mongodb从另一个json对象内的json对象中搜索

时间:2018-05-16 08:47:18

标签: mongodb

考虑这个文件:

{
 "id":1,
 "name":"A",
 "lastName":"AA",
 "friends":{
   "f1":{"name":"X", "lastName":"XX"},
   "f2":{"name":"Y", "lastName":"YY"}
  }
}

我想搜索姓名为“Y”的朋友,但不知道密钥是“f2”......密钥可能是任何东西。我知道我可以将“朋友”设置为数组,但我不想这样做。

1 个答案:

答案 0 :(得分:1)

你去了:

db.collection.aggregate({
    $addFields: {
        "friends": {
            $arrayToObject: { // transform the array of key-value pairs back into a subdocument
                $filter: {
                    input: {
                        $objectToArray: "$friends" // transform the "friends" subdocument into an array of key-value pairs
                    },
                    as: "this",
                    cond: {
                        $eq: [ "$$this.v.name", "Y" ] // we only want the ones where the name is "Y"
                    }
                }
            }
        }
    }
})