我有一系列字典,我必须在其中进行查询。查询将像" name"是" a"那么"价值"应该是" 2"。
{
"t": "m",
"y": "n",
"A":[
{
"name": "x",
"value": "1"
},
{
"name": "y",
"value": "2"
},
{
"name": "z",
"value": "1"
}
]
}
在上面,我想知道什么是"值"是" 1"当" name"是x。 我还需要查询,其中" name"是" x"那么价值应该是" 2"和"名称"是" y"那么"价值"应该是" 1"
答案 0 :(得分:5)
如果要使用嵌入式文档的多个字段进行查询,则必须使用$elemMatch来查询数组中的嵌入文档。所以你的查询应该是这样的:
db.collection.find( {
"A": { $elemMatch: { name: "x", value: "1" } }
})
如果您想要在同一查询中包含(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" } } }
]
})
如果您想要在同一查询中包含(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" } } }
]
})
答案 1 :(得分:0)
一种方法是使用$unwind和$match来获得所需的结果 $ unwind将展开数组A,然后使用$ match我们可以选择匹配的文档。
示例查询
db.collectionname.aggregate([
{$unwind:"$A"},
{$match:{"A.name":"x", "A.value":"1"}}
])
示例结果
{ "_id" : ObjectId("59c9ee65f1287059437fa3ac"), "t" : "m", "y" : "n",
"A" : { "name" : "x", "value" : "1" } }
答案 2 :(得分:0)
我正在使用它并且它正在工作。
db.collection.find(
{
$and:[
{"A.name":"x", "A.value": "2"},
{"A.name":"y", "A.value": "3"},
{"t": "m"}
]
}
以上将给出“t”为“m”的所有记录,其中名称为“x”的字典值为“2”,名称为“y”的字典的值为“3”。