2014-12-05 56 views
0

我有具有结构下方显示一个JSON文件:蒙戈化JSON名称搜索

{ 
    "125": { 
     "name": "sample name one", 
     "age" : 22, 
    }, 
    "126": { 
     "name": "sample name two", 
     "age" : 27, 
    }, 
    "127": { 
     "name": "sample name three", 
     "age" : 21, 
    } 
} 

我要回了125所代表的对象,即下面的对象:

{ 
    "name": "sample name one", 
    "age" : 22, 
} 

我已经尝试了以下查询从控制台,但我无法得到我需要的结果: db.persons.find({"125": {$exists: true}})

我想知道如何查询数据库以返回我需要的数据。感谢您的任何帮助。

回答

1
db.persons.find({"125": {$exists: true}}) 

将返回整个文档,即具有“125”键,不仅是“125”键。

如果您只需要返回“125”,你应该用投影,将它作为第二个参数:寻找

db.persons.find({"125": {$exists: true}}, {"125": 1}) 

然后,您将得到包含“125”的重要文件,无需任何其他键(除了文件的_id)

要省略的文档_id,您需要使用:

db.persons.find({"125": {$exists: true}}, {"125": 1, _id: 0}) 

编辑:

您是否考虑将数组用于具有重复模式的子文档?这会更自然,习惯,也给你一些额外的可能性。

0

在通过JSON的键/场/名蒙戈查询,用$exists操作

db.things.find({ '125' : { $exists : true } });