1

Is there any way to convert a field inside a nested array of object in a query ?

Here is a simple exemple :

My collection :

{ _id: 1, quizzes: [ { _id: 1, question: "bla bla 1"}, { _id: 2, question: "bla bla 2"}, ... ] },
{ _id: 2, quizzes: [ { _id: 1, question: "bla bla 1"}, ... ] }

Currently, my _id are ObjectId, I want to convert all of them including quizzes._id to string.

So here is the expected final result

{ _id: "1", quizzes: [ { _id: "1", question: "bla bla 1"}, { _id: "2", question: "bla bla 2"}, ... ] },
{ _id: "2", quizzes: [ { _id: "1", question: "bla bla 1"}, ... ] }

Here is what I got so far :

db.collection.aggregate([
{
        $addFields: {
            _id: { $toString: "$_id" }, // OK
            quizzes: { $map: { input: "$quizzes", in: { $toString: '$$this._id' }}}
])

But this is wrong, each quizze Object is fully transformed to a string, not just the id.

I am using Mongo 3.4.

1 Answer 1

1

You need to return an object so instead of in: { $toString: '$$this._id' } it should be:

{ _id: { $toString: '$$this._id' }, question: "$$this.question" }

try:

db.collection.aggregate([
    {
        $addFields: {
            _id: { $toString: "$_id" },
            quizzes: { $map: { input: "$quizzes", in: { _id: { $toString: '$$this._id' }, question: "$$this.question" } }}
        }
    }
])

Mongo Playground

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

2 Comments

hello mickl, thank you for your quick answer. Your solution works. But my real object "quizze" has a lot of fields. Moreover, more can be added in the futur. Is there a way to avoid listing all of them in my in: expression ?
@loonis you can use $mergeObjects like here: stackoverflow.com/questions/53934300/…

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.