db.data.insert({userAjax: 'sean',date:'26/04/2014',latv:'78.134123', lonv:'43.
342123', distance:'1.23', hours:'0', minutes:'4', seconds:'21', speed: '1.04' })

db.data.insert({userAjax: 'sean',date:'26/04/2014',latv:'78.134123', lonv:'43.
342123', distance:'1.23', hours:'0', minutes:'4', seconds:'21', speed: '1.04' })

db.data.insert({userAjax: 'sean',date:'25/04/2014',latv:'78.134123', lonv:'43.
342123', distance:'0.43', hours:'0', minutes:'2', seconds:'47', speed: '1.33' })

db.data.insert({userAjax: 'sean',date:'25/04/2014',latv:'78.134123', lonv:'43.
342123', distance:'0.43', hours:'0', minutes:'7', seconds:'55', speed: '1.33' })

this is a sample structure of my collection. on the website I need to display the dates but only the latest insert for that date,

The data is comming from the mobile phone(geolocation) through ajax and on the client side the latest date that was inserted has to be displayed.

有帮助吗?

解决方案

Well presumably you are sorting by date for a given user so:

db.data.find({ "userAjax": "sean" }).sort({ "date": -1 }).limit(1)

Gives you just one result at the latest date for that user.

On the other hand if you are looking for the last result in each day then you can do this with the help of the .aggregate() function:

db.data.aggregate([
    { "$match": { "userAjax": "sean" } },
    { "$project": {
        "_id": { 
            "date": {
                "year": { "$year": "$date" },
                "month": { "$month": "$date" },
                "day": { "$dayOfMonth": "$date" }
            }
        },
        "userAjax": "$userAjax",
        "date": "$date",
        "latv": "$latv", 
        "lonv": "$longv", 
        "distance": "$distance", 
        "hours": "$hours",
        "minutes": "$minutes", 
        "seconds": "$seconds", 
        "speed": "$speed" 
    }},
    { "$sort": { "_id": -1 } },
    { "$group": {
        "_id": { "$first": "$_id" },
        "userAjax": { "$first": "$userAjax" },
        "date": { "$first": "$date" },
        "latv": { "$first": "$latv" }, 
        "lonv": { "$first": "$longv" },
        "distance": { "$first": "$distance" },
        "hours": { "$first": "$hours" },
        "minutes": { "$first": "$minutes" }, 
        "seconds": { "$first": "$seconds" }, 
        "speed": { "$first": "$speed" }
    }}
])

Which is a lot more terse, but that is what you want.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top