0

I have the following query mongoDB

{
    "name": "juan",
    "class": {
        "name": "person"  // is the field of another collection.
    }
}

and what I want to achieve is the following

{
    "name": "juan",
    "class": "person"
}

But I need everyone's support to achieve the above.

2
  • Try to look up $projection in docs. Commented Jun 12, 2020 at 1:07
  • @ Márius Rak thanks i will look for information Commented Jun 12, 2020 at 1:16

2 Answers 2

1

If all you need is for the data to be returned in the structure you specified, you can use a projection with a find query:

db.collection.find({}, { name: 1, class: '$class.name' });

Hope this helps.

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

1 Comment

Adelekam Thanks for sharing your answer.
1

I assume that you want to update the multiple documents, then bellow query will be helpful:

db.collection.update(
  { },
  [
    {
      $set: {
        'class': '$class.name'
      }
    }
  ],
  { multi:true }
)

3 Comments

@ingShravil.py Thanks for sharing your answer.
I would like to suggest you, to be clear in the OP from next time. As in this case it was not clear whether you wanted to update or to find.
@ingShavil.py Sorry, I will be more precise with my questions, but thanks for your reply.

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.