MongoDB的基本操作有:添加 删除 更新 和 读取
启动MongoDB Shell:命令行输入mongo(Centos 7)
[root@jans test]# mongo MongoDB shell version: 2.6.12 connecting to: test Server has startup warnings: 2017-08-31T17:54:18.621+0800 [initandlisten] 2017-08-31T17:54:18.621+0800 [initandlisten] ** WARNING: Readahead for /var/lib/mongodb is set to 4096KB 2017-08-31T17:54:18.621+0800 [initandlisten] ** We suggest setting it to 256KB (512 sectors) or less 2017-08-31T17:54:18.621+0800 [initandlisten] ** http://dochub.mongodb.org/core/readahead >
添加文档:
> db.test.insert({"key_a":"value_a"}) WriteResult({ "nInserted" : 1 }) > db.test.insert({"key_b":"value_b"}) WriteResult({ "nInserted" : 1 })
读取文档:
find()可查询多个符合条件的文档,findOne()只查询一个,
> db.test.find() { "_id" : ObjectId("5a12da411c97109757a27d5d"), "key_a" : "value_a" } { "_id" : ObjectId("5a12dab51c97109757a27d5e"), "key_b" : "value_b" }
> db.test.findOne() { "_id" : ObjectId("5a12da411c97109757a27d5d"), "key_a" : "value_a" }
> db.test.findOne({"key_b" : "value_b"}) { "_id" : ObjectId("5a12dab51c97109757a27d5e"), "key_b" : "value_b" } > db.test.findOne({"_id" : ObjectId("5a12da411c97109757a27d5d")}) { "_id" : ObjectId("5a12da411c97109757a27d5d"), "key_a" : "value_a" }
更新文档:
> db.test.insert({"key_c":"value_c"}) WriteResult({ "nInserted" : 1 })
> db.test.findOne({"key_c" : "value_c"}) { "_id" : ObjectId("5a12e0a38710e2c2442eda15"), "key_c" : "value_c" }
> db.test.update(db.test.findOne({"key_c":"value_c"}), {"new_key_c" : "new_value_c","key_c" : "value_c"}) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test.findOne({"key_c":"value_c"}) { "_id" : ObjectId("5a12e0a38710e2c2442eda15"), "new_key_c" : "new_value_c", "key_c" : "value_c" }
删除文档:
> db.test.remove({"key_c":"value_c"}) WriteResult({ "nRemoved" : 1 }) > db.test.findOne({"key_c":"value_c"}) null