phoenix13

导航

 

http://docs.mongodb.org/manual/tutorial/getting-started-with-the-mongo-shell/     Getting Started with the mongo Shell

http://docs.mongodb.org/manual/reference/glossary/   Glossary

0.

mongod.exe : the server

mongo.exe:   the shell

 

collection ---- a table in relational DB

  A grouping of MongoDB documents. A collection is the equivalent of an RDBMS table. 

document  ---- a entry in relational table

  A record in a MongoDB collection and the basic unit of data in MongoDB.

 

 

1. show all db/ collections

show dbs
show collections

http://docs.mongodb.org/manual/reference/mongo-shell/ 

 

2. display current database that you're using

db

3. switch database

use <database name>

4. insert

db.<collection name>.insert(<json data>)

db.users.insert({'name':'steve','age':'1'})

  python

richard ={"name":"Richard Kreuter"}
people.insert(richard)

5. save

db.users.save({'name':'steve','age':'1'})

 http://stackoverflow.com/questions/16209681/what-is-the-difference-between-save-and-insert-in-mongo-db

6. find (输出)

db.<collection name>.find()

db.users.find()
db.users.find({a:1})

find with format

db.users.find().pretty()

specifying field

db.u.findOne({"name":"haha"},{"name":true})
// return name and _id
db.u.findOne({"name":"haha"},{"name":true,"_id":false})
// only return name
db.u.findOne({"name":"haha"},{"name":1,"_id":0})
// true =1, false =0

 

7. update a document

  http://docs.mongodb.org/manual/reference/operator/update-field/

  7.1 rewplace a document

db.u.update({"_id":"123"},{"popu":100})

    python

score = scores.find_one({'student_id':1, 'type':'homework'})
score['review_date'] = datetime.datetime.utcnow()
scores.update({'student_id':1, 'type':'homework'}, score)

  7.2 using $set

db.users.update({"_id":"apple"},{$set:{"country":"RU"}})

    python

scores.update({'student_id':1, 'type':'homework'},
                      {'$set':{'review_date':datetime.datetime.utcnow()}})

  7.3 find object, change and save

> db.users.find().pretty()
{
        "_id" : ObjectId("53e2b118441a819bd2b7cad5"),
        "name" : "nkdsnckdsn",
        "age" : "1"
}
{
        "_id" : ObjectId("53e2bba8441a819bd2b7cada"),
        "name" : "apple",
        "age" : "2"
}
{
        "_id" : ObjectId("53e2bbb2441a819bd2b7cadb"),
        "name" : "banana",
        "age" : "3"
}
> var h = db.users.findOne({"name":"apple"})
> h
{
        "_id" : ObjectId("53e2bba8441a819bd2b7cada"),
        "name" : "apple",
        "age" : "2"
}
> h.age = '3'
3
> db.users.save(h)
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

  python

score = scores.find_one({'student_id':1, 'type':'homework'})
score['review_date'] = datetime.datetime.utcnow()
scores.save(score)

8. import

import db

mongorestore [db foldername]

import json file into db

mongoimport -d students -c grades < grades.json

http://docs.mongodb.org/manual/reference/program/mongoimport/

 

9. greater, less, greater or equal, less or equal

http://docs.mongodb.org/manual/reference/operator/query/                 

Query and Projection Operators

 

db.u.find({"student":{$gt:50}})

 10. $exists, $regex, $type

Type Number
Double 1
String 2
Object 3
Array 4
Binary data 5
Undefined 6
Object id 7

http://docs.mongodb.org/manual/reference/bson-types/               BSON Types

find all documents whose name type is double

db.u.find({name:{$type:1}})

where the name has a "q" in it, and the document has an email field.

db.users.find({ name : { $regex : "q" }, email : { $exists: true } } );

 11. $or

find all documents in the scores collection where the score is less than 50 or greater than 90

db.scores.find({$or:[{score:{$lt:50}},{score:{$gt:90}}]})

 12. dot

{ product : "Super Duper-o-phonic", 
  price : 100000000000,
  reviews : [ { user : "fred", comment : "Great!" , rating : 5 },
              { user : "tom" , comment : "I agree with Fred, somewhat!" , rating : 4 } ],
  ... }

Write a query that finds all products that cost more than 10,000 and that have a rating of 5 or better.

db.catalog.find({price:{$gt:10000},"reviews.rating":{$gte:5}})

 13. sort(), skip(), limit()

always in this order : sort, skip, limit

db.u.find().sort({student:-1})
db.u.find().limit(10)
db.u.find().skip(20)

python

collection.find().sort('field', pymongo.ASCENDING):

 

14. cursor

cur=db.u.find();null;
 cur.hasNext()
while(cur.hasNext())  printjson(cur.next())

 15. upsert (if document exist then insert, otherwise create new one)

db.foo.update( { username : 'bar' }, { '$set' : { 'interests': [ 'cat' , 'dog' ] } } , { upsert : true } );

   python

stuff.update({'_id':'bat'}, {'friend':'ball', 'cousin':'glove'}, upsert=True)

stuff.update({'_id':'bat'}, {'_id':'bat', 'friend':'ball', 'cousin':'glove'}, upsert=True)

stuff.update({'_id':'bat'}, {'$set': {'friend':'ball', 'cousin':'glove'}}, upsert=True)

 16. load js

mongo --shell [db name]   homework2.js

 17. dump

mongorestore folder_name

 18. drop(delete) database

db.dropDatabase()

 

posted on 2014-08-07 07:47  phoenix13  阅读(225)  评论(0编辑  收藏  举报