我有Json,其值类似于state_city详细信息,其中包含诸如哪个城市属于哪个州的信息-
需要查询它的特定州名,这将为我提供属于该州的所有城市。
db.collection.find({ “计数”:10, “ state.name”:“ MP” })
[
{
"collection": "collection1",
"count": 10,
"state": [
{
"name": "MH",
"city": "Mumbai"
},
{
"name": "MH",
"city": "Pune"
},
{
"name": "UP",
"city": "Kanpur"
},
{
"name": "CG",
"city": "Raipur"
}
]
},
{
"collection": "collection2",
"count": 20,
"state": [
{
"name": "MP",
"city": "Indore"
},
{
"name": "MH",
"city": "Bhopal"
},
{
"name": "UP",
"city": "Kanpur"
},
{
"name": "CG",
"city": "Raipur"
}
]
}
]
答案 0 :(得分:0)
以下查询将是解决方案。
db.collection.find({ "count": 10, "state":{"name": "MP"}})
对于更复杂的查询,还可以使用 $ elemMatch 。
答案 1 :(得分:0)
您必须使用聚合查询仅获取数组中匹配的元素:
db.collection.aggregate([{
$unwind: "$content.state"
},
{
$match: {
"content.state.name": "MH",
"count": 10
}
},
{
$group: {
_id: "$content.state.city",
}
},
{
$addFields: {
key: 1
}
},
{
$group: {
_id: "$key",
cities: {
$push: "$_id"
}
}
},
{
$project: {
_id: 0,
cities: 1
}
}
])
此查询将返回:
{
"cities": [
"Pune",
"Mumbai"
]
}