1

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

6
  • in your question table is not an object, it looks like an array of objects. Commented May 29, 2020 at 14:17
  • table mean to collection. sorry Commented May 29, 2020 at 14:18
  • Your condition and/or is not possible. Is has to be either one of them? You need to satisfy both condition or either one of them? Commented May 29, 2020 at 14:20
  • do you mind posting an expected result? Commented May 29, 2020 at 14:21
  • Hmmm... in the end I need the object with foo and bar (if any) only those with status of ready. Commented May 29, 2020 at 14:21

1 Answer 1

1

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"
            ]
          }
        }
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

1 Comment

can I do it with find only please?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.