Skip to content

Instantly share code, notes, and snippets.

@loonison123
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save loonison123/031c6f3e8ea639529f27 to your computer and use it in GitHub Desktop.

Select an option

Save loonison123/031c6f3e8ea639529f27 to your computer and use it in GitHub Desktop.
Common Mongo Snippets
// Some data
{ "_id" : 4, "grades" : [ { grade: 80, mean: 75, std: 8 },
{ grade: 85, mean: 90, std: 5 },
{ grade: 90, mean: 85, std: 3 } ] }
// Update records based on multiple field matches
db.studenst.update(
grades: {
$elemMatch: {
'grade': {
$lte: 90
},
'mean': {
$gt: 80
}
}
},
{
$set: {
'grades.$.std': 6
}
})
// Add multiple items to an array
db.inventory.update(
{ _id: 2 },
{ $addToSet: { tags: { $each: [ "camera",
"electronics",
"accessories" ] } } })
// Array Update Operators
//http://docs.mongodb.org/manual/reference/operator/update-array/
// Update parameters
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
// Update specific fields
db.books.update(
{ item: "Divine Comedy" },
{
$set: {
price: 18 ,
"isbn.publisher": 2222
},
$inc: { stock: 5 }
})
// Remove Field
db.books.update( { _id: 11 }, { $unset: { stock: 1 } } )
db.collection.find( {arrayName : {$exists:true}, $where:'this.arrayName.length>1'} )
var query = Query.EQ("author", "Ernest Hemingway");
var cursor = books.Find(query);
foreach (var book in cursor) {
// do something with book
}
var firstBook = cursor.FirstOrDefault();
foreach (var task in tasks.Find(query).SetSkip(100).SetLimit(10)) {
// do something with task
}
// Return specified fields
db.inventory.find( { type: 'food' }, { item: 1, qty: 1 } )
// Get a collection
db.collection([[name[, options]], callback);
// Working with ObjectIds, making readable and stringifying
ObjectId(entity._id).toString();
// Insert entity/entities (With lookup values, after inserting, you could lookup
// the values and then you will have the latest from db after inserting)
collection.insert(arrToAdd, function (err, writeConcern) {
if (err) throw err;
// WriteConcern gives you n statistics on what was inserted, etc...
})
// Add to array only if it DOESN'T exist
{
$addToSet: {
tags: ['awesome']
}
}
// Add to multiple to array only if it DOESN'T exist
{
$addToSet: {
tags: {
$each: ['awesome', 'priority']
}
}
}
// Using toArray
collection.find({}, {}).toArray(function (err, docs) {
// Do something with docs
});
// Remove all items that equals a specified value
collection.update({}, {
$pull: {
tags: ['priority']
}
})
// Query if at least one element exists in an array
db.person.find({
'aliases.1' : {
$exists: true
}
})
// Query if at least one elment exists in an array (ineffecient method)
db.person.find({
$where: {
'this.aliases.length': {
$gt: 0
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment