Getting the correct query in Mongodb -
i'm trying simple query subfield out of collection. far keep getting entire field should correct print out subfield i'm looking for?
i'm trying list titles (only) of movies rank of less 9.2 , @ least 5 votes, print titles in alphabetical order.
this query far incorrect , returns whole object. how can return rank , votes of jungle book? thank in advance.
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" }
you need have filter/query in first parameter. second parameter set of booleans properties should return.
db.ratings.find({title: {$exists:true}, rank:{$lt : 9.2}, votes: {$gte : 5 } }, {_id:0, title:1}).sort({title:1})
this return set looks this:
[{"title" : "jungle book"}, {"title" : "spawn"}]
if want titles, , not in object form use "distinct" here:
db.ratings.distinct('title', {title: {$exists:true}, rank:{$lt : 9.2}, votes: {$gte : 5 } });
the distinct query should sorted default. if want sort different way you'll need use aggregate query.
i've run exact set of code against local install:
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>
Comments
Post a Comment