0

Is it possible to find in a nested array the max date and show its price then show the parent field like the actual price.

The result I want it to show like this :

{
    "_id" : ObjectId("5547e45c97d8b2c816c994c8"),
    "actualPrice":19500,
    "lastModifDate" :ISODate("2015-05-04T22:53:50.583Z"),
    "price":"16000"
}

The data :

db.adds.findOne()
    {
            "_id" : ObjectId("5547e45c97d8b2c816c994c8"),
            "addTitle" : "Clio pack luxe",
            "actualPrice" : 19500,
            "fistModificationDate" : ISODate("2015-05-03T22:00:00Z"),
            "addID" : "1746540",
            "history" : [
                    {
                            "price" : 18000,
                            "modifDate" : ISODate("2015-05-04T22:01:47.272Z"),
                            "_id" : ObjectId("5547ec4bfeb20b0414e8e51b")
                    },
                    {
                            "price" : 16000,
                            "modifDate" : ISODate("2015-05-04T22:53:50.583Z"),
                            "_id" : ObjectId("5547f87e83a1dae00bc033fa")
                    },
                    {
                            "price" : 19000,
                            "modifDate" : ISODate("2015-04-04T22:53:50.583Z"),
                            "_id" : ObjectId("5547f87e83a1dae00bc033fe")
                    }
            ],
            "__v" : 1
    }

my query

db.adds.aggregate(
    [
    {   $match:{addID:"1746540"}},
    {   $unwind:"$history"},

    {   $group:{
            _id:0,
            lastModifDate:{$max:"$historique.modifDate"}
        }
    }
])

I dont know how to include other fields I used $project but I get errors thanks for helping

1 Answer 1

3

You could try the following aggregation pipeline which does not need to make use of the $group operator stage as the $project operator takes care of the fields projection:

db.adds.aggregate([
    {   
        "$match": {"addID": "1746540"}
    },
    {
        "$unwind": "$history"
    },        
    {
        "$project": {
            "actualPrice": 1,
            "lastModifDate": "$history.modifDate",
            "price": "$history.price"
        }
    },
    {
        "$sort": { "lastModifDate": -1 }
    },
    {
        "$limit": 1
    }
])

Output

/* 1 */
{
    "result" : [ 
        {
            "_id" : ObjectId("5547e45c97d8b2c816c994c8"),
            "actualPrice" : 19500,
            "lastModifDate" : ISODate("2015-05-04T22:53:50.583Z"),
            "price" : 16000
        }
    ],
    "ok" : 1
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes the $group stage was unnecessary

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.