代码之家  ›  专栏  ›  技术社区  ›  Probine Business

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

  •  0
  • Probine Business  · 技术社区  · 7 年前

    请考虑此文档:

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

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   dnickless    7 年前

    好了:

    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"
                        }
                    }
                }
            }
        }
    })