1

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
            }
        }
    ]
}

1 Answer 1

1

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"});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.