通常很难让 MongoDB 处理模棱两可或参数化的 json 键。我遇到了类似的问题,最好的解决方案是修改架构,使子文档的成员成为数组中的元素。
但是,我认为这会让你接近你想要的(所有代码都应该直接在 Mongo shell 中运行)。假设您有以下文件:
db.collection.insert({
"_id": "doc1",
"field1": {
"subfield1": {"key1": "value1"},
"subfield2": ["a", "b", "c"],
"subfield3": 1,
"subfield4": "a"
},
"field2": "other content"
})
db.collection.insert({
"_id": "doc2",
"field1": {
"subfield1": {"key2": "value2"},
"subfield2": [1, 2, 3],
"subfield3": 2,
"subfield4": "b"
},
"field2": "yet more content"
})
然后,您可以运行一个聚合命令来提升 的内容,field1
同时忽略文档的其余部分:
db.collection.aggregate({
"$group":{
"_id": "$_id",
"value": {"$push": "$field1"}
}})
这使得所有subfield*
键成为对象的顶级字段,并且该对象是数组中的唯一元素。这很笨拙,但可行:
"result" : [
{
"_id" : "doc2",
"value" : [
{
"subfield1" : {"key2" : "value2"},
"subfield2" : [1, 2, 3],
"subfield3" : 2,
"subfield4" : "b"
}
]
},
{
"_id" : "doc1",
"value" : [
{
"subfield1" : {"key1" : "value1"},
"subfield2" : ["a","b","c"],
"subfield3" : 1,
"subfield4" : "a"
}
]
}
],
"ok" : 1