Reputation: 424
db.posts.find({comments:{$elemMatch:{user:'Khan'}}})
db.posts.find({comments:{$elemMatch:{user:'khan'}}})
this is really a mind twister for me, above are two $elemMatch search queries i use in MongoDb shell, i typed these in Code Studio, when i copy paste first line in shell it return nothing, when i copy paste the 2nd line in shell, expected result is returned...
both are same then why the response is different???
following is the posts collection in the db
{
"_id": {
"$oid": "5eda19c6a38d4418e311e43b"
},
"title": "post1",
"body": "body of post 1",
"category": "news",
"tags": [
"news",
"events"
],
"user": {
"name": "author name",
"status": "author"
},
"date": "Fri Jun 05 2020 15:09:10 GMT+0500 (Pakistan Standard Time)",
"likes": 6,
"comments": [
{
"user": "mehtab",
"body": "this is some comments 1",
"date": "Fri Jun 05 2020 16:47:17 GMT+0500 (Pakistan Standard Time)"
},
{
"user": "khan",
"body": "this is some comments 2",
"date": "Fri Jun 05 2020 16:47:17 GMT+0500 (Pakistan Standard Time)"
},
{
"user": "saad",
"body": "this is some comments 3",
"date": "Fri Jun 05 2020 16:47:17 GMT+0500 (Pakistan Standard Time)"
}
]
}
MongoDB 4.2.7 Community
Upvotes: 1
Views: 33
Reputation: 71120
Your two queries are indeed different. One has the first letter upper-cased, and one does not, and string-matching is case-sensitive.
Uppercase K:
db.posts.find({comments:{$elemMatch:{user:'Khan'}}})
Lowercase k:
db.posts.find({comments:{$elemMatch:{user:'khan'}}})
Upvotes: 2
Reputation: 455
I'm sure you want to know why this happens and me too, but following the MongoDB Documentation, if you specify a single query predicate in the $elemMatch expression, $elemMatch is not necessary.
Since the $elemMatch only specifies a single condition, the $elemMatch expression is not necessary, and instead you can use the following query:
db.posts.find(
{ "comments.user": "Khan" }
)
Upvotes: 1