0

I have a users collection in MongoDB with this sample row:

[
    {
        "_id": 1,
        "name": "John Doe",
        "comments": [
            {
                "_id": 100,
                "content": "Comment 100",
                "post": "1000"
            },
            {   
                "_id": 101,
                "content": "Comment 101",
                "post": "1000"
            }
        ]
    }
]

I want to project users and comments data after converting _id fields into id. So I used the following query:

db.users.aggregate([
  {
    $project: {
      _id: 0,
      id: '$_id',
      name:1
      comments: {
        _id: 0,
        id: '$_id',
        content: 1,
      },
    }
  }
])

Now the users _id field is successfully converted. But the comments id field is equal to _id of users collection instead of comments.

[
  {
    "id": 1,
    "name": "john Doe",
    "comments": [
      {
        "id": 1,
        "content": "comment 100"
      },
      {
        "id": 1,
        "content": "comment 101"
      },
    ]
  }
]

How can I achieve the right result.

1 Answer 1

1

you should use $map in project like this

https://mongoplayground.net/p/H4pueuejYdf

db.collection.aggregate([
  {
    "$project": {
      _id: 0,
      id: "$_id",
      name: 1,
      comments: {
        "$map": {
          "input": "$comments",
          "as": "c",
          "in": {
            id: "$$c._id",
            content: "$$c.content",
            post: "$$c.post"
          }
        }
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. Doesn't this cause performance issues compared with simple $projection?
So because your comments fields is array you couldnt change value as other value , there is another way to unwind project and then group , but need more process ,
if my answer help you I appreciate to accept my answer

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.