Reputation: 39437
I have this collection in my test
database.
[test] 2014-02-11 18:45:48.338 >>> db.blog.posts.find( );
{
"_id" : ObjectId("52ee29bdb8eb94049427886a"),
"comments" : [
{
"author" : "Jane",
"comment" : "yes, yes, it is",
"votes" : 5
}
],
"content" : "This is a post",
"id" : 5
}
{
"_id" : ObjectId("52f95c5bd1fe9c171fe4344b"),
"comments" : [
{
"author" : "Jane",
"comment" : "yes, yes, it is",
"votes" : 5
},
{
"author" : "Nick",
"comment" : "test",
"votes" : 10
},
{
"author" : "John",
"comment" : "new one",
"votes" : 4
}
],
"content" : "This is a post",
"id" : 5
}
When I run this find query:
[test] 2014-02-11 18:45:50.318 >>> db.blog.posts.find({ "comments" : {author : "Jane", comment: "yes, yes, it is", votes: 5}} );
I get both documents back.
But if I run this find query
[test] 2014-02-11 18:46:18.428 >>> db.blog.posts.find({ "comments" : {author : "Jane", comment: "yes, yes, it is", votes: {$gte : 5}}} );
I get no documents back.
Why is that? How come == 5 gives me results back but >= 5 does not return anything.
Upvotes: 0
Views: 50
Reputation: 2625
Very interesting case, to be honest. But, I think there
are more efficient commands to get what you need.
I have solved your issue as follows.
db.posts.find({
"comments": {
"$elemMatch": {
author : "Jane",
comment: "yes, yes, it is",
votes: {"$gte" : 5}
}
}
});
and the result is as follows:
The reason the first OP query works and the second OP query doesn't is because
in the first case there are documents that meet the exact form being queried.
The second OP query uses a modifier, hence the need to wrap with $elemMatch.
More information from the official MongoDB site can be found here:
http://docs.mongodb.org/manual/reference/operator/projection/elemMatch/
Hope this helps.
Upvotes: 1