Skip to content

Instantly share code, notes, and snippets.

@jobsamuel
Last active August 29, 2015 14:06
Show Gist options
  • Save jobsamuel/0b403944e725f0be99ed to your computer and use it in GitHub Desktop.
Save jobsamuel/0b403944e725f0be99ed to your computer and use it in GitHub Desktop.
Playing with MongoDB - Finding documents
/////////////////////////////
// Playing with MongoDB ////
// 2 - Finding documents //
//////////////////////////
// MongoDB Driver instances.
var MongoClient = require('mongodb').MongoClient
, ObjectId = require('mongodb').ObjectID
// Set the database and collection name you want to connect to perform the query.
, database = "college"
, collection = "students";
// Since ObjectIds contain a timestamp, which tells you when the document was created,
// the next function converts a timestamp into an ObjectID. Allowing you to make queries
// by date without the necessity of inserting a timestamp key into your document schema
// (unless you have persnickety requirements for creation times, like resolutions of less than a second,
// synchronization across app servers, etc).
function objectIdFromTimestamp(timestamp) {
// Convert string date to Date object (otherwise assume timestamp is a date).
if (typeof(timestamp) == 'string') {
timestamp = new Date(timestamp);
}
// Convert date object to hex seconds since Unix epoch.
var hexSeconds = Math.floor(timestamp/1000).toString(16)
// Create an ObjectId with that hex timestamp.
, constructedObjectId = ObjectId(hexSeconds + "0000000000000000");
return constructedObjectId;
}
MongoClient.connect('mongodb://localhost:27017/' + database, function(err, db) {
// A simple error handler.
if (err) throw err;
// Define the mongodb collection where your app will perform the query.
var cursor = db.collection(collection)
// Define the query parameters of the documents you are looking for.
, query = {
_id: {
$gt: objectIdFromTimestamp("2014/9/4"),
$lt: objectIdFromTimestamp("2014/9/6")
},
language: "EN"
}
// Define the filds you want to display after a succesful operation.
, projection = {
_id: false,
student: false,
'personal_info.gender': false,
'personal_info.email': false,
career: false,
grades: false
};
// MongoDB Find operation.
// The operation will display only 10 documents
// because of .limit(10)
cursor.find(query, projection).limit(10).each(function(err, doc) {
// It will display an error, if there is one.
// Alse, it will display the returned documents
// and close the database safely when the operation ends.
if (err) {
throw err
} else if (doc != null) {
console.log(doc);
} else {
db.close();
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment