时间:2021-07-01 10:21:17 帮助过:9人阅读
启动Mongodb
1. 按配置文件启动
mongod -config mongod.cfg
2. 指定参数启动
mongod --dbpath "F:\Database\Mongodb\Data" --logpath "F:\Database\Mongodb\Log\mongod.log"
3. 安装服务
mongod --dbpath "F:\Database\Mongodb\Data" --logpath "F:\Database\Mongodb\Log\mongod.log" --serviceName "mongodb" --serviceDisplayName "mongodb" --install
连接Mongodb
cmd 执行
1. 默认配置
mongo
2. 连接字符串
mongo mongodb://localhost
CRUD操作
Create
1. 插入单个文档
db.logs.insertOne()
var data = {"UserId" : 10, "Operate" : "登录" , "CreateTime" : new Date() }; db.logs.insertOne(data);
返回
{ "acknowledged" : true, //是否写入成功 "insertedId" : ObjectId("5e929706fe1792ce954f65f1") //插入行的Id }
2. 插入多个文档
var data = [ {"UserId": 10, "Operate": "登录", "CreateTime": new Date() }, {"UserId": 10, "Operate": "点击首页", "CreateTime": new Date() }, {"UserId": 10, "Operate": "查看列表", "CreateTime": new Date() } ] db.logs.insertMany(data);
返回
{ "acknowledged" : true, "insertedIds" : [ ObjectId("5e9297dbfe1792ce954f65f2"), ObjectId("5e9297dbfe1792ce954f65f3"), ObjectId("5e9297dbfe1792ce954f65f4") ] }
3. db.collection.insert
insert可以插入单个文档(对象)/ 多个文档(对象的数组)
var data = [ {"UserId": 10, "Operate": "登录", "CreateTime": new Date() }, {"UserId": 10, "Operate": "点击首页", "CreateTime": new Date() }, {"UserId": 10, "Operate": "查看列表", "CreateTime": new Date() } ] db.logs.insert(data);
返回
单个文档
WriteResult({ "nInserted" : 1 })
多个文档
BulkWriteResult({ "writeErrors" : [ ], "writeConcernErrors" : [ ], "nInserted" : 3, "nUpserted" : 0, "nMatched" : 0, "nModified" : 0, "nRemoved" : 0, "upserted" : [ ] })
4. 若不存在插入
在日常操作中,经常需要写不存在就写入的操作,在mongodb一种更新机制(upsert),若不存在就写入。
db.logs.update({ "UserId": 20 }, { "UserId": 20, "Operate": "登录", "CreateTime": new Date() }, { upsert: true })
支持upsert参数的方法
Read
db.logs.find({"UserId":20});
db.logs.findOne({"UserId":10});
Update
1. 更新单个文档
db.logs.updateOne({ "_id": ObjectId("5e92b6d4fe1792ce954f6613") }, { $set: { "CreateTime": new Date() } })
2. 更新多个文档
db.logs.updateMany({ "UserId": 10 }, { $set: { "CreateTime": new Date() } })
Delete
1. 删除单个文档
db.logs.deleteOne({ "UserId": 20 })
2. 删除多个文档
db.logs.deleteMany({ "UserId": 10})
转发请标明出处:https://www.cnblogs.com/WilsonPan/p/12685393.html
参考文章
Collection Methods — MongoDB Manual
【Mongodb】入门
标签:match reference replace ocs dbf targe web 点击 blog