- 
                Notifications
    You must be signed in to change notification settings 
- Fork 0
mongo basic commad
        nougatang edited this page Oct 9, 2017 
        ·
        1 revision
      
    - assign a value to variable
>x = 200
200
- and cal it
>x/5
40
- you can use std lib of JavaScript
>Math.sin(Math.PI/2);
1
> new Date(2010/1/1);
ISODate("1970-01-01T00:00:02.010Z")
> "hello,world".replace("world","mongo");
hello,mongo
- and you can define a JS function and call it
> function factorial(n){
... if(n<=1) return 1;
... return n*factorial(n-1);
... }
> factorial(5);
120
- test is mongo default db,mongo will connect to this database after shell started,you can use db to check which db in use
>db
test
- list all db
> show dbs
admin  0.000GB
local  0.000GB
test   0.000GB
- and switch your current db
> use local
switched to db local
- and you can use db.help() for db's help or db.mycoll.help() for collection's help
- firstly. create a local variable like this
> person = {"name":"jiangbo",
... "sex":"man",
... "birth":new Date()}
{
	"name" : "jiangbo",
	"sex" : "man",
	"birth" : ISODate("2017-09-28T02:48:50.128Z")
}
- second. save the person variable into a collection by use method insert()
> db.people.insert(person);
WriteResult({ "nInserted" : 1 })
there is no collection named people before we insert person into collection people,when we insert,collection people was created. you can use show collections see all collection in current db.
- you can use find() to see collection's data.
> db.people.find()
{ "_id" : ObjectId("59cc658d9d608c39be913831"), "name" : "jiangbo", "sex" : "man", "birth" : ISODate("2017-09-28T02:48:50.128Z") }
method update accept tow argument at least. first argument is condition. second argument is new data. for example. add "friends" key for person and update it.
- first. alter person, add a key named "friends".
> person.friends=["xiaohua",
... "xiaohong"]
[ "xiaohua", "xiaohong" ]
> person
{
	"name" : "jiangbo",
	"sex" : "man",
	"birth" : ISODate("2017-09-28T02:48:50.128Z"),
	"friends" : [
		"xiaohua",
		"xiaohong"
	]
}
- second. replace old to new
> db.people.update({name:"jiangbo"},person)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.people.find()
{ "_id" : ObjectId("59cc658d9d608c39be913831"), "name" : "jiangbo", "sex" : "man", "birth" : ISODate("2017-09-28T02:48:50.128Z"), "friends" : [ "xiaohua", "xiaohong" ] }
use remove to remove doc from collection. the argument is condition for method remove
> db.people.remove({name:"jiangbo"})
WriteResult({ "nRemoved" : 1 })
- for start your mongodb shell,but make sure add your mongodb'path to profile
$ mongo
- for remote connection
$ mongo ${hostname}:${port}/${dbname}
- dump mongodb data
$ mongodump -h ${dbhost} -d ${dbname} -o ${dbdirectory}
- restore mongodb data
$ mongorestore -h ${hostname}:${port} -d dbname ${path}