【问题标题】:MongoDB : aggregate $project take array current itemMongoDB:聚合 $project 获取数组当前项目
【发布时间】:2017-07-10 07:55:39
【问题描述】:

您好,我有这样的 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",

【问题讨论】:

  • 如何从日期数组中确定当前日期,它始终是数组中的第一个元素还是您需要对数组进行降序排序然后获取第一个元素?
  • 你能展示示例文件吗?
  • codeshare.io/CrEXp 这是结果
  • codeshare.io/bbKVy 这是我的猫鼬模式
  • 更新您的帖子,而不是粘贴外部网址。

标签: node.js mongodb mongoose aggregation-framework


【解决方案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

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 1970-01-01
    • 2018-09-23
    • 2012-10-24
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 2013-03-10
    • 1970-01-01
    相关资源
    最近更新 更多