MongoDBメモ


SELECT

//select * from table
db.table.find()         //with out ID
db.table.find().pretty()//pretty output

//select title from table where title = "MongoDB tutorial"
db.table.find({"title":"MongoDB tutorial"},{"id":0,"title":1}) 

//select * from table where likes > 50 and likes < 100
db.table.find({"likes":{$gt:50,$lt:100}})

//select * from table where by = "mongodb" or title = "MongoDB tutorial"
db.table.find({ $or: [{"by": "mongodb"},{"title": "MongoDB tutorial"}]}).pretty()
db.table.find({"likes":{$gt:50,$lt:100}})

//select * from table where name in ("java","c++","php")
//$nin => not in
db.table.find({ "course":{$in: ["java","c++","php"]}).pretty()

//select title from table limit 2;
db.table.find({},{"title":1,_id:0}).limit(2)
//SELECT Array
//$all
//$size
//$slice

INSERT

db.table.insert({
    title: 'MongoDB tutorial',
    description: 'MongoDB is a Nosql database',
    by: 'mongodb', 
    url: 'http://www.mongodb.org.cn', 
    tags: ['mongodb', 'database', 'NoSQL'],
    likes: 100  
})

UPDATE

//update table set title = 'MongoDB' where title = 'MongoDB tutorial'         
db.table.update({'title':'MongoDB tutorial'},{$set:{'title':'MongoDB'}})//update one
db.table.update({'title':'MongoDB tutorial'},{$set:{'title':'MongoDB'}},{multi:true})//update multi
//replace one record
db.table.save({     
    "_id" : ObjectId("56064f89ade2f21f36b03136"), 
    "title": 'MongoDB tutorial2',
    "description": 'MongoDB is a Nosql database2',
    "by": 'mongodb2', 
    "url": 'http://www.mongodb.org.cn', 
    "tags": ['mongodb', 'database'],
    "likes": 200 
    }
)

DELETE

//delete from table where title = 'MongoDB tutorial'
db.table.remove({'title':'MongoDB tutorial'})