1
votes

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'
}
3
I don't think that question is asking about querying multiple documents though - willmahon
your question is not clear, okay for multiple conditions you can use $elemMatch operator. - turivishal

3 Answers

1
votes

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"] }
            }
        }
    }
}
])
0
votes

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

0
votes

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