2012-07-10 62 views
2

我有一个简单的结构化文档是这样的:查询部分对象 - MongoDB的

"people" : [ 
    { 
     "id" : "6241863", 
     "amount" : 5 
    } 
], 

人们可以包含多个元素。我已经成功地得到这个工作:

db.village.findOne({"people": {"$in": [{"id": "6241863", "amount": 5}]}}) 

但我想忽略量和搜索包含ID为6241863和任何人量的任何文件。

+0

您无法在find查询中检索单个文档数组的一部分。你必须在客户端做 – 2012-07-10 14:50:47

+0

老兄你是如何保存这样的数据,我有这样一个shema product_video:[{thum_src:String,video_name:String,video_path:String}],我不知道如何保存数据 – paynestrike 2012-12-07 00:54:42

回答

5

按照advanced query documentation,你可以用dot notation for reaching into objects混合阵列值的查询。下面是使用您的模式的示例:

$ mongo 
MongoDB shell version: 2.1.0 
connecting to: test 
> db.users.save({_id: 1, friends: [{id: 2, name: 'bob'}]}) 
> db.users.find({friends: {id: 2, name: 'bob'}}) 
{ "_id" : 1, "friends" : [ { "id" : 2, "name" : "bob" } ] } 

> db.users.find({'friends.id': 2}) 
{ "_id" : 1, "friends" : [ { "id" : 2, "name" : "bob" } ] } 

> db.users.find({'friends.name': 'bob'}) 
{ "_id" : 1, "friends" : [ { "id" : 2, "name" : "bob" } ] } 

> db.users.find({'friends.name': 'ted'}) 
> 
+0

如果在用户以上存在一个对象,比如包含'users'和'admins'的'roles',你仍然只想搜索用户,你会怎么做? – 2017-09-29 16:39:32

0

尝试与

db.village.findOne({"people" : { "$in" : [{ "id" : "6241863" , "amount" : { "$ne" : null } }]}})