0

My documents in collection,

[
    {
        "_id": {
            "uuid": "aaa",
            "sectionId": "1"
        },
        "name": "tmp"
    },
    {
        "_id": {
            "uuid": "bbb",
            "sectionId": "2"
        },
        "name": "tmp"
    },
    {
        "_id": {
            "uuid": "ccc",
            "sectionId": "3"
        },
        "name": "tmp"
    }
]

Need something like this in output:

_id.uuid -> slot_id

_id.sectionId -> id

name -> slot_name

[
    {
        "slot_id": "aaa",
        "id": "1",
        "slot_name": "tmp"
    },
    {
        "slot_id": "bbb",
        "id": "2",
        "slot_name": "tmp"
    },
    {
        "slot_id": "ccc",
        "id": "3",
        "slot_name": "tmp"
    }
]

I have an ugly looking working in Java, but I am quite sure mongodb has a nice way of doing it..

Please help!! Thanks in advance.

1 Answer 1

1

Using find you can use projection stage like this:

db.collection.find({},
{
  "_id": 0,
  "slot_id": "$_id.uuid",
  "id": "$_id.sectionId",
  "slot_name": "$name"
})

Example here

Using aggregate simply use $project like this:

db.collection.aggregate([
  {
    "$project": {
      "_id": 0,
      "slot_id": "$_id.uuid",
      "id": "$_id.sectionId",
      "slot_name": "$name"
    }
  }
])

Example here

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

Comments

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.