1

Using MongoDB queries:
1. How do I find the object with _id A3?
2. How would I update object with _id A3 to A4?

Please note: Database is an array of objects where one key has an array of objects

[{
"project_name": "ProjectA",
"issues":[{"issue_title":"TitleA1", "_id":"A1"},
          {"issue_title":"TitleA2","_id":"A2"},
          {"issue_title":"TitleA3","_id":"A3"}]
},
{
"project_name": "ProjectB",
"issues":[{"issue_title":"TitleB1", "_id":"B1"},
          {"issue_title":"TitleB2","_id":"B2"},
          {"issue_title":"TitleB3","_id":"B3"}]
}
]

1 Answer 1

2

You can use the dot notation to $match your object by nested _id and use $unwind with $replaceRoot to promote nested object to the top level:

db.collection.aggregate([
    {
        $unwind: "$issues"
    },
    {
        $match: { "issues._id": "A3" }
    },
    {
        $replaceRoot:{ newRoot: "$issues" }
    }
])

Mongo Playground

the positional operator can be used to update that one:

db.col.updateOne({ "project_name": "ProjectA", "issues._id": "A3" }, { $set: { "issues.$._id": "A4" } })
Sign up to request clarification or add additional context in comments.

5 Comments

I'm not sure that works because the starting dataset is an array... could you please confirm that your code can bypass 2 arrays? I'm not sure if I'm testing the code wrong or if the code can't access double arrays. Maybe it needs $elemMatch somewhere but I tried so many times and couldn't get it to work
So is it like this: mongoplayground.net/p/8yPdPJ1C2cB ? or can you show exactly how single object looks like?
Ah yes, just like in that playground. Question 1 would be how to return this object {"issue_title":"TitleA3","_id":"A3"} by itself. I tried the code you suggested but it's giving me error and maybe we need to integrate "aggregate" somehow?
@wongz modified my answer
thanks, the first code works. The second one may need aggregate as well?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.