在Mongodb中获取正确的查询

时间:2014-11-12 16:41:24

标签: mongodb

我试图让这个简单的查询从集合中获取一个子域。到目前为止,我只是继续得到整个领域,所以我应该纠正什么才能打印出我正在寻找的子字段?

我试图列出排名低于9.2且至少有5票的所有电影的标题(仅限),按字母顺序打印标题。

这是我的查询到目前为止,但它不正确,只返回整个对象。我怎样才能让它只返回Jungle Book的排名和票数?非常感谢你提前。

db.collections.find({" title":{$ exists:true}},{" _id":0," rank":{$ lt:9.2}})

{ "_id" : ObjectId("10"), "rank" : 6, "votes" : 8.8, "title" : "Jungle Book" }

{ "_id" : ObjectId("11"), "rank" : 8, "votes" : 8.7, "title" : "Spawn" }

1 个答案:

答案 0 :(得分:0)

您需要在第一个参数中包含过滤器/查询。第二个参数是一组布尔值,它应该返回它的属性。

db.ratings.find({title: {$exists:true}, rank:{$lt : 9.2}, 
    votes: {$gte : 5 } }, {_id:0, title:1}).sort({title:1})

这将返回一个如下所示的集合:

[{"title" : "Jungle Book"}, {"title" : "Spawn"}]

如果您只想要标题,而不是对象形式,则可以使用" distinct"这里:

db.ratings.distinct('title', {title: {$exists:true}, 
   rank:{$lt : 9.2}, votes: {$gte : 5 } });

默认情况下应该对distinct查询进行排序。如果您想以不同的方式对其进行排序,则需要使用聚合查询。

我已经针对本地安装运行了这组完整的代码:

MongoDB shell version: 2.4.8
connecting to: test
rs0:PRIMARY> db.ratings.insert({rank:6, votes:8.8, title:"Jungle Book"});
rs0:PRIMARY> db.ratings.insert({rank:8, votes:8.7, title:"Spawn"});
rs0:PRIMARY> db.ratings.find({title: {$exists:true}, rank:{$lt : 9.2}, votes: {$gte : 5 } }, {_id:0, title:1}).sort({title:1})
{ "title" : "Jungle Book" }
{ "title" : "Spawn" }
rs0:PRIMARY> db.ratings.distinct('title', {title: {$exists:true}, rank:{$lt : 9.2}, votes: {$gte : 5 } });
[ "Jungle Book", "Spawn" ]
rs0:PRIMARY>
相关问题