How to sort a collection by date in MongoDB? - node.js

I am using MongoDB with Node.JS. I have a collection which contains a date and other rows. The date is a JavaScript Date object.
How can I sort this collection by date?

Just a slight modification to #JohnnyHK answer
collection.find().sort({datefield: -1}, function(err, cursor){...});
In many use cases we wish to have latest records to be returned (like for latest updates / inserts).

db.getCollection('').find({}).sort({_id:-1})
This will sort your collection in descending order based on the date of insertion

Sorting by date doesn't require anything special. Just sort by the desired date field of the collection.
Updated for the 1.4.28 node.js native driver, you can sort ascending on datefield using any of the following ways:
collection.find().sort({datefield: 1}).toArray(function(err, docs) {...});
collection.find().sort('datefield', 1).toArray(function(err, docs) {...});
collection.find().sort([['datefield', 1]]).toArray(function(err, docs) {...});
collection.find({}, {sort: {datefield: 1}}).toArray(function(err, docs) {...});
collection.find({}, {sort: [['datefield', 1]]}).toArray(function(err, docs) {...});
'asc' or 'ascending' can also be used in place of the 1.
To sort descending, use 'desc', 'descending', or -1 in place of the 1.

Sushant Gupta's answers are a tad bit outdated and don't work anymore.
The following snippet should be like this now :
collection.find({}, {"sort" : ['datefield', 'asc']} ).toArray(function(err,docs) {});

This worked for me:
collection.find({}, {"sort" : [['datefield', 'asc']]}, function (err, docs) { ... });
Using Node.js, Express.js, and Monk

collection.find().sort('date':1).exec(function(err, doc) {});
this worked for me
referred https://docs.mongodb.org/getting-started/node/query/

With mongoose it's as simple as:
collection.find().sort('-date').exec(function(err, collectionItems) {
// here's your code
})

Additional Square [ ] Bracket is required for sorting parameter to work.
collection.find({}, {"sort" : [['datefield', 'asc']]} ).toArray(function(err,docs) {});

if your date format is like this : 14/02/1989 ----> you may find some problems
you need to use ISOdate like this :
var start_date = new Date(2012, 07, x, x, x);
-----> the result ------>ISODate("2012-07-14T08:14:00.201Z")
now just use the query like this :
collection.find( { query : query ,$orderby :{start_date : -1}} ,function (err, cursor) {...}
that's it :)

With mongoose I was not able to use 'toArray', and was getting the error: TypeError: Collection.find(...).sort(...).toArray is not a function.
The toArray function exists on the Cursor class from the Native MongoDB NodeJS driver (reference).
Also sort accepts only one parameter, so you can't pass your function inside it.
This worked for me (as answered by Emil):
collection.find().sort('-date').exec(function(error, result) {
// Your code
})

Related

MongoDB distinct function and alphabetical sorting

I have a simple question on sorting results from the distinct command in mongodb.
I'm using Monk in my NodeJS app to get categories from my simple DB:
db.getCollection('citazioni').distinct('category')
But how can I apply a sorting function like I successfully do when I find documents with:
collection.find({}, {sort: {'_id': -1}} ??
Thank you!
Monk has support for the underlying node.js native driver distinct() method and its signature is
Collection.prototype.distinct = function (field, query, fn) { ... }
As you can see from that commit that it implements the distinct method of the node native driver collection type via the .col accessor on the selected collection object:
this.col.distinct(field, query, promise.fulfill);
Thus you can implement it together with the native JavaScript sort() method as follows :
// Perform a distinct query against the category field
db.getCollection('citazioni').distinct('category', function(err, categories) {
console.log(categories.sort());
}
Concatenate it:
db.getCollection('citazioni').distinct('category').sort({'_id': -1})
In a Node app with Mongoose:
collection.distinct('citazioni').sort({'_id': -1}).exec(function(e2, categories) {
... etc ...
}

"not contains" query in SailsJS Waterline

How can I create the not contains query that returns true if the item does not contain a certain value. I'm running mongoDB if it is relevant.
I can use the contains successfully however receive an error when I introduce the not. I've tried it with find and where but get the same regex error both times. I can add the exact error if its relevant.
Working version:
model.find({attribute: {'contains': value}})
.exec(function(err, users) {
// happy code
});
The following complains about some regex error:
model.find({attribute: {not: {'contains': value}}})
.exec(function(err, users) {
// sad code
});
There was an issue raised and closed in 2013 about this. Maybe something changed recently?
https://github.com/balderdashy/waterline/issues/22
Alexei, I don't think this is supported by waterline currently. There is a related issue which is marked as feature and that you can track:
https://github.com/balderdashy/waterline/issues/666
So far, you can only use native feature of Mongodb I think.
Model.native(function(err, collection) {
collection.find({
"attribute" : {
$ne : value, //Not Equal
//OR
$nin : [value1, value2]// Not In
}
}).toArray(function(err, docs) {
if (err) return callback(err, docs);
res.json(null, docs);
});
});

Limit find using Monk in mongoDB

I have a large collection of documents.
I want to get the first 100 of these.
From the Monk Docs, this is the find method I am using
var documents = [];
users.find({}, function (err, docs){
for(i=0;i<100;i++)
documents.push(docs[i]);
});
This is highly wasteful since, the entire documents are anyway retrieved.
I want something like this (from the mongodb docs)
docs = db.users.find().limit( 100 );
I tried in monk,
users.find({}, function (err, docs){
for(i=0;i<docs.length;i++)
documents.push(docs[i]);
}).limit(100);
But it gives an error saying that there is no function limit in the "promise" object that is returned before it.
Is there such an option in Monk to limit the number of documents?
Yes, you can pass it as an option in the second parameter:
users.find({}, { limit : 100 }, function (err, docs){
for(i=0;i<docs.length;i++)
documents.push(docs[i]);
});
This comes from the native node mongodb driver, which monk wraps via mongoskin:
http://mongodb.github.io/node-mongodb-native/markdown-docs/queries.html#query-options
You could pass options object as a second parameter to .find():
users.find({}, {limit: 100}, next);
If you want add pagenumber and sorting, here is how to do it with monk:
users.find({}, {limit: 100, skip: pagenumber, sort: {'username': 1}})
where limit is for page size, skip is page number, sorting result by username ascending.

How to do field selection on find() in the mongodb native driver?

I am using the mongodb native driver for node.js and can't get to work the field selection. What I want to do is to limit fields to name. I do not want the 'last' in the output.
I am doing this:
db.collection("test").find({},[{'name':true,'last':false}]).toArray(function(err, results) {
console.dir(results);
});
But the log prints:
[ { _id: 524b53588aa4f388de1c2ddb },
{ _id: 524b53548aa4f388de1c2dda } ]
So there is no name in the output.
Update:
I have tried an object instead of array -- did not work. The reason is really mixing inclusion and exclusion. You can't mix it. When I only had "name":true it worked.
If you are using latest mongodb 3.0 nodejs driver, then try this code:
db.collection('test').find({}).project({name: 1, last: 1}).toArray();
The field selection argument to find is an object, not an array. And you can't mix field inclusion and exclusion (except for _id), so it should be:
db.collection("test").find({}, {'name': true}).toArray(function(err, results) {
console.dir(results);
});
The recommended way of doing this in v3.0 is with the projection field in the options object:
db.collection('test').find({}, {projection: {name: 1}}).toArray()
As mentioned in the accepted answer, you still cannot mix inclusion and exclusion.
See: http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#find
Omit the array:
db.collection("test").find({},{'name':true,'last':false}).toArray(function(err, results) {
console.dir(results);
});

mongodb, get the result line after update

I'm working with mongodb, node.js and socket.io and I'm trying to reduce the number off access to the database. I need to update a line ; and after to return the updated line this is how I do :
db.collection('users').update({_id:targetID}, {$set: { 'property': 'value' }}, {safe:true}, function(err, result) {
db.collection('users').find({_id:targetID}).toArray(function(error, results){
//a socket.io resend the content
});
});
It works, but I really fell like I'm having a useless step here. The callback of the update function seems to be a boolean.
BTW, is there a better documentation than this one : http://docs.mongodb.org/manual/applications/update/ ? I'd like to find a list of properties and methods. The {safe:true} for instance. It seems not working without it but I can't find it in the reference.
Maybe I'm completely wrong and this is not the way I should do it. If you have a better idea... :)
You can use findAndModify to do this efficiently:
db.collection('users').findAndModify(
{_id: targetID}, [],
{$set: { 'property': 'value' }},
{new: true}, // Return the updated doc rather than the original
function(err, result) {
// result contains the updated document
}
);

Resources