Reputation: 1487
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.
Upvotes: 1
Views: 1598
Reputation: 49945
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" } }}
}
}
])
Upvotes: 1