2

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",
5
  • How do you determine the current date from an array of dates, is it always the first element in the array or you need to order the array descending then get the first item? Commented Mar 8, 2016 at 14:48
  • 1
    Can you show sample documents? Commented Mar 8, 2016 at 14:49
  • codeshare.io/CrEXp this is result Commented Mar 8, 2016 at 16:11
  • codeshare.io/bbKVy and this is my mongoose schema Commented Mar 8, 2016 at 16:12
  • 2
    Update your post instead of pasting external Url. Commented Mar 8, 2016 at 16:18

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.