Reputation: 883
What's the correct syntax for finding all docs where, in an array of embedded docs, the username is 'User1'?
These variations have yet to work:
db.collection.find( { to: { username: { $in: [ "User1" ] } } } )
db.collection.find( { to: { $in: [ { username: "User1" } ] } } )
The docs look like:
{
"message" : "Here's a Message",
"to" : [
{
"user" : ObjectId("53aada6f8b10eb0000ec8a90"),
"username" : "User1",
"updated" : ISODate("2014-06-28T19:14:20Z"),
"_id" : ObjectId("53af140c14809099b615d347"),
"read" : {
"marked" : false
}
}
{
"user" : ObjectId("53aada6f8b10eb0000ec8a91"),
"username" : "User2",
"updated" : ISODate("2014-06-28T19:15:20Z"),
"_id" : ObjectId("53af140c14809099b615d348"),
"read" : {
"marked" : false
}
}
]
}
Upvotes: 1
Views: 27
Reputation: 12240
You want to use dot notation to access elements of an array. The correct syntax is:
db.collection.find({"to.username": { $in: ["User1"] }});
The $in operator is used when you're looking for multiple values. If you're searching with only one value the more efficient query is a simple equality check:
db.collection.find({"to.username": "User1"});
Upvotes: 1