Need Help for MongoDB Query

25 views
Skip to first unread message

Ali

unread,
May 11, 2016, 12:43:25 PM5/11/16
to mongodb-user
Hello everybody....... I am new to MongoDB........ I have a document which has a array of times of type string. I want to retrieve all the  values closest to given time and onward.
Here is the document: Please help to write the query. Waiting for your response.
{"St_Name": "CitySquare", 
"Time": ["09:57", "11:57", "12:57", "13:57", "14:57", "15:57", "16:57", "17:57", "18:57", "19:57", "20:57", "21:57", "23:03"]}

Wan Bachtiar

unread,
May 15, 2016, 10:44:53 PM5/15/16
to mongodb-user

I have a document which has a array of times of type string. I want to retrieve all the values closest to given time and onward.

Hi Ali,

One way of achieving what you are after is to utilise MongoDB aggregation pipeline. You can use the $unwind operator to expand the document per Time array element, and then filter the result using $match operator. For example:

// Retrieve all array elements greater than "17:30"
db.collection.aggregate([
    { $match: {"St_Name": "CitySquare" }},
    { $unwind: "$Time" }, 
    { $match: { "Time": { $gte : "17:30" }}}
]);

Depending on the complexity of the application and dataset, you may benefits from storing Time values as date.

I would also recommend to enrol in a free online course at MongoDB University; especially the M101 courses that cover indexes, data modelling, querying, aggregation etc. The next session starts on the 24th May, there’s plenty of time to register.

Regards,

Wan.

Reply all
Reply to author
Forward
0 new messages