从数组中获取元素

Get elements from array

我有一个 collection。让我们从 collection:

中取一个元素
{
    "messages" : {
        "_id" : ObjectId("5503044be4b0e3d1aed29d15"),
        "body" : "Hello YOU!",
        "subject" : "sth"
     }
}

现在是棘手的部分。如何在没有包装器的情况下从 collection 获取元素。如下所示:

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

您可以使用 $project 在文档中添加或重置字段很简单。

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