Reputation: 2181
Given
A collection of products with such structure:
{
product: "Super Duper-o-phonic",
price: 100000000000,
reviews: [
{
user: "fred",
comment: "Great!",
rating: 5
},
{
user: "tom",
comment: "I agree with Fred, somewhat!",
rating: 4
}
]
};
Need to
find all products that cost more than 10,000 and that have a rating of 5 or better.
Here is my solution (which is incorrect):
db.catalog.find({
$and: [
{
price: {
$gt: 10000
}
},
{
"reviews.rating": {
$gte: 5
}
}
]
});
And here is the correct solution:
db.catalog.find({
"price": {
"$gt": 10000
},
"reviews.rating": {
"$gte": 5
}
});
What is the diff between my solution and the right one?
Upvotes: 2
Views: 1352
Reputation: 2011
The two queries should do the same thing, and they did in my few tests. On the other hand, the second is more compact, since $and is implicit when you use just commas.
As you clarified in the comments, the reason why you think that the first query is wrong is that it was marked wrong on MongoDB University. I think you should ask on their forum.
Your solution works, it is just not nice to read.
Upvotes: 2
Reputation: 3302
From the MongoDB documentation:
MongoDB provides an implicit AND operation when specifying a comma separated list of expressions. Using an explicit AND with the $and operator is necessary when the same field or operator has to be specified in multiple expressions.
So, in your case, both queries are functionally identical; however, the explicit $and
operator is unnecessary. It's common practice to leave it out unless you need it.
Upvotes: 2