如何在MongoDB中对嵌入式文档使用$ unwind后获取文档字段?

时间:2017-09-19 06:37:03

标签: php node.js mongodb

我的文档名称为Products,其中包含一个名为comments的嵌入式文档:

{
    "_id" : 1,
    "name" : "test",
    "comments" : [ 
        {
            "_id" : 2,
            "userId" : 3,
            "comment" : "hi",
            "verified" : false,
            "date" : ISODate("2017-09-18T21:21:02.280Z")
        }
    ]
}

我在php中使用此查询来获取评论:

$this->mongo_db->aggregate("Products", [['$unwind' => '$comments'], ['$sort' => ['comments.date' => -1]], ['$project' => ["name" => 1, "comments" => 1]], ['$match' => ['comments.verified' => false]], ['$project' => ["comments._id" => 1, "comments.date" => 1, "comments.dateD" => ['$dateToString' => ['format' => '%Y-%m-%d', 'date' => '$comments.date']]]]]);

这是我的结果:

{ 
    "_id" : 1,
    "comments" : { 
        "_id" : 2,
        "comment" : "hi", 
        "date" : ISODate("2017-09-18T21:21:02.280Z"), 
        "dateD" : "2017-09-18"
     } 
}   

这是我想在mongodb中使用聚合的结果:

{ 
    "_id" : 1,
    "name": "test",
    "comments" : { 
        "_id" : 2,
        "comment" : "hi", 
        "date" : ISODate("2017-09-18T21:21:02.280Z"), 
        "dateD" : "2017-09-18"
     } 
}

现在我想获得产品名称,我写 name => 1项在$ project中但没有返回。当我删除第二个$ project管道时,它工作正常。

1 个答案:

答案 0 :(得分:1)

您只需使用$ addFields管道

即可
$this->mongo_db->aggregate("Products", [['$unwind' => '$comments'], ['$sort' => ['comments.date' => -1]], ['$project' => ["name" => 1, "comments" => 1]], ['$match' => ['comments.verified' => false]], ['$addFields' => ["comments.dateD" => ['$dateToString' => ['format' => '%Y-%m-%d', 'date' => '$comments.date']]]]]);