Aramayis  Mkrtchyan
Aramayis Mkrtchyan

Reputation: 349

MongoDB : aggregate $project take array current item

Hi I have mongodb query like this .

.aggregate(
            [
                { $match : { comment_box : "somdata" } },

                { $project : {
                    comment : 1,                      
                        created_at: 1,
                        current_date: "$replies.created_at",
                    },
                    dateDifference: { $subtract: [ new Date(), "$created_at"] }
                }},
            ]
        )

Imagine that I want to get created_at value from replies array in current date field. but this query returns

current_date: [
   "2016-03-08T13:48:27.882Z",
   "2016-03-08T14:26:22.194Z"
]

instead of current created_at value of each element from this array

I have tried many ways but got errors

current_date: "$replies.0.created_at",
current_date: "$replies.$.created_at",
current_date: "$$replies.created_at",

and etc

please help me to retrieve data like this

current_date:"2016-03-08T13:48:27.882Z",

Upvotes: 2

Views: 325

Answers (1)

binki
binki

Reputation: 8308

I’m assuming you want the latest comment date. In that case, you can just take the $max:

current_date: { $max: '$replies.created_at' }

Demo:

> 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 }

Notice how the document with an empty replies array gets null.

Upvotes: 1

Related Questions