简体   繁体   中英

Mongodb : How to convert a field inside a nested array of object

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM