Jon Sud
Jon Sud

Reputation: 11661

How to query array inside nested object using mongoose?

I have complex object stored in my mongodb look like this:

     const collectionFromMongodb = [
      {
        id: ObjectID(),
        text: 'blabla',
        data: {
          foo: [
            { id: ObjectID(), status: 'ready' },
            { id: ObjectID(), status: 'notready' },
          ],
          bar: [
            { id: ObjectID(), status: 'ready' },
            { id: ObjectID(), status: 'notready' },
          ],
        },
      },
    ];

I want to query the all the object (find) but the object that return will have in foo and bar only object that status are ready. (data.foo.[?].status === 'ready' and/or data.bar.[?].status === 'ready').

I expect to get all the object (since my filter is only on data), but the fields of foo and bar contains only the status of 'ready'.

Note: In foo and bar I have data size of 1mb.

How to do that with mongoose query? is it possible to do? or just query all object and use filter and map?

I did this but not works, because its gets all the statuses in data.foo:

find('data.foo': { $elemMatch: { status: 'ready' })

Upvotes: 1

Views: 97

Answers (1)

Koodies
Koodies

Reputation: 550

Hope this is what you need. Change the $match pipeline to whatever u need to find.

https://mongoplayground.net/p/o1qk4wla5C6

db.collection.aggregate([
  {
    $match: {
      "data.bar.status": "ready"
    }
  },
  {
    $project: {
      "data.foo": {
        $filter: {
          input: "$data.foo",
          as: "foo",
          cond: {
            $eq: [
              "$$foo.status",
              "ready"
            ]
          }
        }
      },
      "data.bar": {
        $filter: {
          input: "$data.bar",
          as: "bar",
          cond: {
            $eq: [
              "$$bar.status",
              "ready"
            ]
          }
        }
      }
    }
  }
])

Upvotes: 1

Related Questions