Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongodb find a document with all subdocuments satisfying a condition

Tags:

mongodb

I have Game collection in my DB:

var game = {
  players: [{username:"user1", status:"played"},
            {username:"user2", status:"accepted"}]
}

As far as I understand query like this: db.games.find({"players.status":"played"}) will give me all games where at least one player has status "played". How can I find games with ALL players having status "played"?

like image 602
andr111 Avatar asked May 07 '12 21:05

andr111


People also ask

How do you find documents with a matching item in an embedded array?

Use $match With $eq to Find Matching Documents in an Array in MongoDB. Use $match With $all to Find Matching Documents in an Array in MongoDB.

How do I search multiple documents in MongoDB?

You can query for multiple documents in a collection with collection. find() . The find() method uses a query document that you provide to match the subset of the documents in the collection that match the query.

How do I fetch nested data in MongoDB?

Accessing embedded/nested documents – In MongoDB, you can access the fields of nested/embedded documents of the collection using dot notation and when you are using dot notation, then the field and the nested field must be inside the quotation marks.

What does find () do in MongoDB?

In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents.


1 Answers

If you only have one other status than "played" use the query:

db.games.find({ "players.status": { $ne:"accepted" } })

You can adjust the query to handle more status values, as long as they are all known at the time of the query.

like image 80
Asya Kamsky Avatar answered Sep 22 '22 14:09

Asya Kamsky