Reputation: 32331
I am storing document in format of an array as shown below in mongodb .
{
"plans": [
{
"status": "cooking",
"timestamp": "2016-01-15"
},
{
"status": "washing ",
"timestamp": "2014-01-18"
},
{
"status": "enjoying some tea",
"timestamp": "2014-02-22"
}
],
"username": "preethiJain"
}
Is it possible to write a query in such a way that , it will return the sort the elements of an array based on timestamp and returns the first one from the result .
For example in the above case , it will return me the element
{
"status": "washing ",
"timestamp": "2014-01-18"
}
Currently i am reading the whole structure and sorting it based on programically way and returning the first one , but this is taking a lot of time for processing the request .
Please let me know if this is possible or not .
Upvotes: 0
Views: 463
Reputation: 26012
You can do it with Aggregation Framework. The query should be like :
db.test.aggregate(
{$match : {"username" : "preethiJain"}},
{$unwind: "$plans"},
{$sort: {"plans.timestamp":1}},
{$limit : 1}
)
Upvotes: 1