0

I'm using MongoDB v5 with NodeJS (no Mongoose). Let's say I have a collection structured the following way. This specific setup (an ObjectId nested inside an object contained inside an array contained inside another object) is trickier to handle in an aggregation because nested.users can not be unwinded then rebuilt again into an array (because $group doesn't support deep properties) and using $lookup with let/as/pipeline works only if as contains something different than nested.users.user, in which case the object loses it's original shape.

{
  nested: {
    users: [
      {
        user: ObjectId('...'),
        status: 'pending',
      },
      {
        user: ObjectId('...'),
        status: 'pending',
      },
    ]
  }
}

I need to rebuild the document to populate nested.users.user (while preserving it's original shape) by using a single aggregation pipeline. I expect the following outcome:

{
  nested: {
    users: [
      {
        user: {
          _id: ObjectId('...'),
          name: 'User 1',
        },
        status: 'pending',
      },
      {
        user: {
          _id: ObjectId('...'),
          name: 'User 2',
        },
        status: 'approved',
      },
    ]
  }
}

Reshaping the data is not an option. This is just an example of a more general problem I'm experiencing. I need a programmactic way to populate ObjectIds nested inside arrays inside objects in different collections.

So far I've tried:

  • unwinding and rebuilding nested.users into an array
  • using $lookup with pipeline combined with $replaceRoot, couldn't reassemble nested.users
2
  • Could you transform the data in NodeJS instead of mongo? e.g. read data from mongo, map over the documents in node and add the IDs, send a large update back to mongo. Commented Aug 12, 2024 at 8:28
  • I didn't quite get "can not be unwound then rebuilt again" part. Could you show in which way it did not work. If I understand, you want to pull user objects from another collection by ID. In this case $lookup is unavoidable. Hint: an example collections on mongoplayground.net will increase chances of an answer. Commented Aug 12, 2024 at 8:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.