Quark986
Quark986

Reputation: 35

Get elements from array

I have an collections. Let's take one element from collection:

{
    "messages" : {
        "_id" : ObjectId("5503044be4b0e3d1aed29d15"),
        "body" : "Hello YOU!",
        "subject" : "sth"
     }
}

and now the tricky part. How to get elements from collection without wrapper. Like below:

{    
  "_id" : ObjectId("5503044be4b0e3d1aed29d15"),
  "body" : "Hello YOU!",
  "subject" : "sth"
}

Upvotes: 0

Views: 84

Answers (1)

Sede
Sede

Reputation: 61273

It is simple you can use $project to add or reset a field within the document.

db.collection.aggregate([
    { 
        "$project": {
            "_id": "$messages._id",
            "body": "$messages.body", 
            "subject": "$messages.subject"
         } 
     }
])

Upvotes: 3

Related Questions