简体   繁体   中英

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' })

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM