嗨,我有像这样的mongodb查询。
.aggregate(
[
{ $match : { comment_box : "somdata" } },
{ $project : {
comment : 1,
created_at: 1,
current_date: "$replies.created_at",
},
dateDifference: { $subtract: [ new Date(), "$created_at"] }
}},
]
)
想象一下,我想从当前日期字段中的回复数组中获取created_at值。但是这个查询返回
current_date: [
"2016-03-08T13:48:27.882Z",
"2016-03-08T14:26:22.194Z"
]
而不是此数组中每个元素的当前created_at值
我尝试了很多方法但却出错了
current_date: "$replies.0.created_at",
current_date: "$replies.$.created_at",
current_date: "$$replies.created_at",
等
请帮我检索这样的数据
current_date:"2016-03-08T13:48:27.882Z",
答案 0 :(得分:1)
我假设你想要最新的评论日期。在这种情况下,您可以选择$max
:
current_date: { $max: '$replies.created_at' }
演示:
> db.comments.insert({_id: 0, replies: [{created_at: new Date('2017-04-03')}, {created_at: new Date('2017-02-03')} ]})
WriteResult({ "nInserted" : 1 })
> db.comments.insert({_id: 1, replies: []})
WriteResult({ "nInserted" : 1 })
> db.comments.aggregate([{$project: {current_date: {$max: '$replies.created_at'}}}])
{ "_id" : 0, "current_date" : ISODate("2017-04-03T00:00:00Z") }
{ "_id" : 1, "current_date" : null }
请注意具有空replies
数组的文档如何获得null
。