Fawad Khalil
Fawad Khalil

Reputation: 367

Accessing embedded documents of mongodb using JSON

The question is: Can I access the embedded documents of a documents in mongodb using JSON selectors after returning the outer document. Let me explain the question with an example:

Suppose Comments have an embedded documents Users. Now first I return Comments document using the code:

var comments = db.Comments.find();

And then I use JSON syntax to return the embedded documents, as mongodb uses JSON objects to store documents (so far I understand/know):

var users = comments['Users'];

I know it is not possible to return embedded documents in mongodb and the way to access Users would be to make seperate document of Users. But, still, I am just asking out of curiosity if this logic would work, as it will help me a lot in coding node.js with mongodb.

Hope that everyone understands the question.

Note: The example is just imaginary so please don't comment about the example being right or wrong, the basic purpose was just to make my question understandable with ease.

Upvotes: 0

Views: 178

Answers (1)

王如锵
王如锵

Reputation: 981

Assuming the structure of Comment:

  {
    _id,
    Users: [
      {
        name
      }
    ]
  }

You can do what you want by aggregate:

  db.Comments.aggregate([
    {$unwind:{path:'$Users'}},
    {$project:{'name':'$Users.name', _id: 0}}
  ])

Upvotes: 1

Related Questions