0

I have an aggregate query that is doing exactly what I want up to this point, but I am stuck transforming the data at the last step. I have the following:

{
    "name": "a",
    "tasks": [ { .. }, { .. }]
},
{
    "name": "b",
    "tasks": [ { .. }, { .. }]
}

all I need to do is map each entry in tasks to a separate result. Sounds incredibly simple to me.

The expected output should be

{ "name": "a", "task": { .. } },
{ "name": "a", "task": { .. } },
{ "name": "b", "task": { .. } },
{ "name": "b", "task": { .. } }

I tried using { $unwind: '$tasks' } in hopes that I could get separate entries, but it only seems to expand the first result. I only get the tasks from a.

I also tried $map but had similar problems.

If necessary, there is an _id inside of each task that could be used for uniqueness. Thats really what I'm trying to accomplish, a map of key-value pairs such as

{ "_id": "idFromTheTask", "name": "a" }
0

1 Answer 1

1

$unwind is the right way unless your tasks array is empty. In that case it will remove such document. To prevent that you can use preserveNullAndEmptyArrays, try:

db.collection.aggregate([
    {
        $unwind: {
            path: "$tasks",
            preserveNullAndEmptyArrays: true
        }
    }
])

An example here

Sign up to request clarification or add additional context in comments.

4 Comments

odd. I am getting 20 results, but there are 40 total tasks among 5 original results. Still not sure why
Actually, the first entry alone has 21 tasks, and using $unwind is still only giving me 20 in robo 3t
I think 20 is the default size of the cursor, maybe you can run .toArray on it or just add { limit: 100 } to control the number of returned documents
you are right, adding toArray() in robo 3t solved the issue

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.