如何在 MongoDB 中查询字典数组? [英] How do I query an array of dictionaries in MongoDB?
问题描述
我有一组字典,我必须在这些字典上进行查询.查询将类似于当名称"为a"时,值"应为2".
I have an array of dictionaries on which I have to make queries. The queries will be like when "name" is "a" then "value" should be "2".
{
"t": "m",
"y": "n",
"A":[
{
"name": "x",
"value": "1"
},
{
"name": "y",
"value": "2"
},
{
"name": "z",
"value": "1"
}
]
}
在上面,我想知道当name"为x时,value"为1"的记录是什么.我还需要进行查询,其中名称"为x",则值应为2",名称"为y",则值"应为1"
In the above, I want to know what are the records whose "value" is "1" when "name" is x. I also need to make queries like, where "name" is "x" then value should be "2" and "name" is "y" then "value" should be "1"
推荐答案
你必须使用 $elemMatch 查询数组中的嵌入文档,如果你想查询嵌入文档的多个字段.所以你的查询应该是这样的:
You have to use $elemMatch to query embedded documents in an array if you want to query with multiple fields of embedded document. So your query should be like this:
db.collection.find( {
"A": { $elemMatch: { name: "x", value: "1" } }
})
如果您想查询具有 (name:"x", value:"1")
或 (name:"y", value:"2")
在同一个查询中,你可以像这样使用 $or
和 elemMatch:
If you want query documents which have (name:"x", value:"1")
or (name:"y", value:"2")
in same query, you can use $or
with elemMatch like this:
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:
If you want query documents which have (name:"x", value:"1")
and (name:"y", value:"2")
in same query, you can use $and
with elemMatch like this:
db.collection.find( {
$and: [
{ "A": { $elemMatch: { name: "x", value: "1" } } },
{ "A": { $elemMatch: { name: "y", value: "2" } } }
]
})
这篇关于如何在 MongoDB 中查询字典数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!