如何在MongoDB中查询字典数组?

has*_*raf 4 mongodb nosql pymongo

我有一系列字典,必须在上面进行查询。查询将类似于“名称”为“ a”,然后“值”应为“ 2”。

{
    "t": "m",
    "y": "n",
    "A":[ 
            {
             "name": "x",
             "value": "1"
            },
            {
             "name": "y",
             "value": "2"
            },
            {
             "name": "z",
             "value": "1"
            }
        ]
}
Run Code Online (Sandbox Code Playgroud)

在上面,我想知道什么是“名称”为x时“值”为“ 1”的记录。我还需要进行类似的查询,其中“名称”为“ x”,然后值应为“ 2”,“名称”为“ y”,然后“值”应为“ 1”

bar*_*ini 6

如果要查询嵌入式文档的多个字段,则必须使用$ elemMatch查询数组中的嵌入式文档。因此,您的查询应如下所示:

db.collection.find( {
  "A": { $elemMatch: { name: "x", value: "1" } }
})
Run Code Online (Sandbox Code Playgroud)

如果你想具有查询文档(name:"x", value:"1") (name:"y", value:"2")在相同的查询,你可以使用$or与elemMatch这样的:

db.collection.find( {
  $or: [
    { "A": { $elemMatch: { name: "x", value: "1" } } },
    { "A": { $elemMatch: { name: "y", value: "2" } } }
  ]  
})
Run Code Online (Sandbox Code Playgroud)

如果要查询具有(name:"x", value:"1") (name:"y", value:"2")在同一查询中的文档,则可以$and与elemMatch一起使用,如下所示:

db.collection.find( {
  $and: [
    { "A": { $elemMatch: { name: "x", value: "1" } } },
    { "A": { $elemMatch: { name: "y", value: "2" } } }
  ]  
})
Run Code Online (Sandbox Code Playgroud)


Cle*_*ath 0

一种方法是使用$unwind$match来获得所需的结果 $unwind 将展开数组 A,然后使用 $match 我们可以挑选出匹配的文档。

示例查询

db.collectionname.aggregate([
      {$unwind:"$A"}, 
      {$match:{"A.name":"x", "A.value":"1"}}
])
Run Code Online (Sandbox Code Playgroud)

结果示例

{ "_id" : ObjectId("59c9ee65f1287059437fa3ac"), "t" : "m", "y" : "n", 
   "A" : { "name" : "x", "value" : "1" } }
Run Code Online (Sandbox Code Playgroud)