willmahon
willmahon

Reputation: 339

How to query and filter multiple documents in mongodb?

I have a collection with 80 documents, each document looks like the one below. Is there a way that I can search through each document's "data" array and find any objects that have a "color" of 'red', all in one query to the mongodb database? or would I have to make 80 different queries to the mongodb database to do this?

{
  _id: 'j3k1jrh123h42',
  data: [
    {name: 'ben', color: 'red'},
    {name: 'tom', color: 'blue'},
    {name: 'will', color: 'red'},
    {name: 'jack', color: 'red'},
    {name: 'bob', color: 'yellow'}
  ],
  class: '8A',
  lastUpdate: '12-05-2021'
}

Upvotes: 1

Views: 1724

Answers (3)

Asma Mubeen
Asma Mubeen

Reputation: 51

You can get records that have an element with color: red by

Model.find({"data.color": "red"})

If you want to filter the data array such that it only has elements with color: red

Model.aggregate([
{
    $match: {
        "data.color": "red"
    }
},
{
    $project: {
        data: {
            $filter: {
                input: "$data",
                as: "doc",
                cond: { $eq: ["$$doc.color", "red"] }
            }
        }
    }
}
])

Upvotes: 1

R2D2
R2D2

Reputation: 10737

You can find easy all documents containing any elements with data.color: red via $match , but if you want the result to contain only the color: red element arrays you can use $filter or $unwind/$match

Upvotes: 0

Joe
Joe

Reputation: 28366

Depending on what you are trying to do you can use aggregtion with $project and $reduce, or with $unwind and $match

Upvotes: 0

Related Questions