Skip to content

Instantly share code, notes, and snippets.

@fabiofumarola
Created May 14, 2015 12:52
Show Gist options
  • Save fabiofumarola/df238517f06500fec317 to your computer and use it in GitHub Desktop.
Save fabiofumarola/df238517f06500fec317 to your computer and use it in GitHub Desktop.
MongoDB Lab
//create a place
var place1 = {
"name" : "10gen HQ",
"address" : "578 Broadway 7th Floor",
"city" : "New York",
"zip" : "10011",
"tags" : [
"business",
"awesome"
]
}
//find
db.places.find()
//find with conditions
db.places.find({ zip: "10011",
tags: "awesome" })
var place2 = {
"name" : "10gen HQ",
"address" : "578 Broadway 7th Floor",
"city" : "New York",
"zip" : "10011",
"tags" : [
"business",
"awesome"
],
"comments" : [
{
"date" : ISODate("2014-10-01T00:00:00Z"),
"author" : "Fabio",
"text" : "best place"
}
]
}
//find nested documents
db.places.find({"comments.author" : "Fabio"})
var place3 = {
"name" : "10gen HQ",
"address" : "578 Broadway 7th Floor",
"city" : "New York",
"zip" : "10011",
"tags" : [
"business",
"awesome"
],
"comments" : [
{
"date" : ISODate("2014-10-01T00:00:00Z"),
"author" : "Fabio",
"text" : "best place",
"score" : 30
}
]
}
db.places.find({"comments.author" : "Fabio"})
db.places.find({"comments.score" : { $gt: 20}})
db.places.find({ "name" : "10gen HQ", "comments.author" : "Fabio" })
db.places.findOne({ "name" : "10gen HQ", "comments.author" : "Fabio" })
db.places.find({ $or : [{ "name" : "10gen HQ" }, {"comments.author" : "Fabio" }]})
db.places.find().sort({"name" : 1, "comments.score" : -1})
db.places.update(
{name : "10gen HQ"},
{ $push :
{ comments :
{ author : "steve",
date : 6/26/2012,
text : "Office hours are great!"
}
}
}
)
db.places.update(
{name : "10gen HQ"},
{ $push :
{ comments :
{ author : "steve",
date : 6/26/2015,
text : "Office hours are great!"
}
}
},
{ multi: true}
)
db.places.find({'comments.author': /^Fr/})
db.places.remove({"name" : "10gen HQ"})
db.places.remove({"name" : "10gen HQ"}, { justOne: true } )
db.posts.ensureIndex({ "location": "2d" })
db.posts.find({"location":{$near:[22,42]}})
//load venues data
use conf
var cursor = db.venues.find()
db.venues.aggregate(
[
{ $group: { "_id": "$location.city", "count": { $sum: 1 } } }
]
)
//index
db.venues.createIndex({"location.country": 1})
//compound index
db.venues.createIndex({"location.country": 1, "location.distance": -1})
//geo index
db.venues.ensureIndex({ "location.geo": "2d" })
//or
db.venues.createIndex({ "location.geo": "2d" })
//query
db.venues.find({"location.geo":{$near:[-122.6600248120735,45.5302342677652]}})
db.venues.find( { "location.geo" :
{ $geoWithin :
{ $box : [ [ 0 , 0 ] ,
[ -122 , 48 ] ]
} } } )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment