|
Mongo db
Installation
1)Download installer from mongo website and run installer
2)Create data directory under disk’s root directory, d:/data/db;
Start mongo db server
Go to installation bin directory, and run command: mongod --dbpath d:/data/db
Database operation
Create database : use DATABASE_NAME
If the database does not exist, then create this database, otherwise, switch to this specific database.
Example
>use runoob
Switched to db runoob
>db
Runoob
>
>show dbs
Local 0.078DG
Admin 0.078G
Create a collection
New database runoob is not shown by using command “show dbs” , need to insert data into this new created database.
>db.runoob.insert ({“name”:”mongodbDEmo”})
WriteResult({“nInserted:1})
>show dbs
Local 0.078G
Admin 0.078 G
Runoob 0.078G
Delete a collection db.runoob.drop()
Delete a database :db.dropDatabase() , delete current database.
>show dbs
Local 0.078G
Admin 0.078G
Runoob 0.078G
>use runoob
Switched to db runoob
>
>db.dropDatabase()
{“dropped”:”runoob”,”ok”:1}
Find all records
Db.user.find() //user is collection name.
Insert a record
Db.user.insert ({“name”:”Jacky”})
Update a record //add a field and update name data.
Db.user.update({“name”:”Jacky”},{“name”:”Jacky tt”,”age”:”30”})
Remove a record
Db.user.remove({“name”:”Jacky”})
Add a field
db.users.update({},{$set:{gender:""}},{multi:1})
Remove a field
db.users.update({},{$unset:{gender:""}},false,true)
Add embedded records
db.multi.insert({"empId":1,"members":[{"name":"Blue1","age":"23","gender":"male"},{"name":"Blue2","age":"33","gender":"female"},{"name":"Blue3","age":"43","gender":"male"}]})
Query embedded records
db.multi.find({"members":{"$elemMatch":{"name":"Blue1","age":"23"}}})
db.multi.find({"empId":1.0})
Linked query
Collection A: users [id, name,email]
Collection B posts[id, author,postId]
author=db.users.findOne({"name":"cindy"})
for (var post=db.posts.find({"author":author.name});post.hasNext();) {
printjson(post.next().postId)};
Aggregation
Filter some fields in query process
db.multi.aggregate({$project:{empId:1}}), get ID and empId only.
db.multi.aggregate({$project:{_id:0,members:1}}) get members field only.
Unwind: split array fields to multiple individual records
db.multi.aggregate({$project:{_id:0,members:1}},{$unwind:"$members"})
var test=db.multi.aggregate({$project:{_id:0,members:1}},{$unwind:"$members"})
for (;test.hasNext();) {
printjson(test.next().members.name)};
test=db.multi.findOne()
printjson(test.members[0].name);
Multi-embedding documents
Auth management
db.createUser({user:"admin",customData:{description:"superuser"},pwd:"admin",roles:[{role:"root",db:"admin"}]})
Show users
Start mongo db server with auth info.
Go to installation bin directory, and run command: mongod --dbpath d:/data/db -auth
db.auth("admin","admin")
Use testdb, then query all records.
|
|