Config
Config. to run MongoDB
- Set
PATH
as system variable (~/.bashrc
) - Create folders
/data/db
and setrw-
permissions to correct user. - start
mongod
Queries
Find
by element
db.getCollection('documentX').find({ _id : ObjectId("5b7e99a9149559198c5024a4") })
by sub-element
db.getCollection('doc').find({ "doc.$id" : ObjectId("5bc6ea45c9979cda5f1a7ed6") })
like
Fields which contains question mark
db.getCollection('doc').find({ "title": /�/ })
sort by
Latest created
db.getCollection('doc').find({}).sort({ "createdAt":-1 })
limit results
db.getCollection('doc').find({}).limit(5)
and / or
db.getCollection('doc').find({
$and : [
{ "subelement.$id" : ObjectId("58b57fcdc998001a00000004") },
{ "field2" : "CAR" }
]
})
date
greater or equal
db.getCollection('doc').find({
"createdAt" : { $gte : new ISODate("2018-10-09 00:00:00.000Z") }
})
not equal
db.getCollection('doc').find({
$and : [
{ "field" : "90" },
{ "field2" : { $ne : 2 } }
]
})
Subquery
Every doc contains a provided_doc, but from provided_doc I cannot go back to doc.
// Obtain all ids from provided_docs which have a competitionId = 90 & regionID != 1
var docs = db.getCollection('provided_doc').find({
$and : [
{ "competitionId" : "90" },
{ "regionID" : { $ne : 1 } }
]
}).map(function(providedDoc) {
return providedDoc._id
});
// search all docs which contain a provided_doc with one of those ids
db.getCollection('doc').find({"doc.$id" : { $in:docs }});
Check for Nulls
Try both options, they may give different results back.
db.getCollection('doc_event').find({"orderNum" : {$exists:false}})
db.getCollection('doc_event').find({ "orderNum" : null })
Update
Only change “firstName” field of this object
db.player.update(
{ "_id" : ObjectId("5b7e77060e885706eb574118") },
{ $set :
{"firstName" : "Sacha"}
}
)
Databases
db
- show current databaseshow dbs
- show all databases with sizeuse $db
- create / select database
drop database
use $db
$db.dropDatabase()
Collections
show collections
- show all collectionsdb.collection.drop()
- drop collection
Create collection
db.createCollection($name, $options {capped, autoIndexId, size, max }) # Parameters
db.createCollection("my-col", { capped : false, autoIndexId : true})
Documents
db.collection.find().pretty()
- query all
Create
db.collection.insert({
title : "First Document",
description : "My first created document",
by : "msanchez",
url : "www.google.es",
tags : ["mongodb", "document", "first"],
likes : 100
})
Misc
see list of changes:
db.getCollection('jv_snapshots').find({"globalId.cdoId": "5b7e77060e885706eb574109"})
Special chars
To select something with specials chars in the same:
db.myCollection.drop() # Collection w. camel case.
db["my-collection"].drop() # Collection w. symbols in the name.