Dalibor Trampota
Dalibor Trampota

Reputation: 25

MongoDB find in array in all documents

I have a collection of documents with this simplified structure:

{
   cards: [
       {
           id: "some string",
           ....
       },{...}{...}{...}
   ]
}

I need to query the whole collection of documents and find those documents where my defined ID of a card matches one of the objects in the array of cards.

I usually fetch all documents and do it locally but this is quite large collection and I have no clue how to achieve this if even possible.

Thank you for your time!

ps: I'm using nodejs mongoose

Upvotes: 0

Views: 327

Answers (2)

mohammad Naimi
mohammad Naimi

Reputation: 2359

db.collection.find({cards:{$elemMatch:{id:{$eq:"some string"}}})

Upvotes: 1

Dalibor Trampota
Dalibor Trampota

Reputation: 25

After playing around with mohammad Naimi's solution I figured the correct syntax:

db.collection.find({ cards:{ $elemMatch: { id: { $eq:"some string" }}}})

Upvotes: 1

Related Questions