插入
在已有的文档中插入一组新值
db.col.update({ },{$set:{“xxx”:“xxxx”}})
效果
> db.col.find().pretty()
{
"_id" : ObjectId("6244268e153444102d14ece9"),
"title" : "MongoDB 教程",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "菜鸟教程",
"url" : "http://www.runoob.com",
"tags" : [
"mongodb",
"database",
"NoSQL",
"xxxx"
],
"likes" : 100,
"test" : "xxxx"
}
{ "_id" : ObjectId("624427281f98d57822e9031c"), "test5" : "OK" }
> db.col.update({ "_id" : ObjectId("6244268e153444102d14ece9")},{$set:{"xxx":"xxxx"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
>
> db.col.find().pretty()
{
"_id" : ObjectId("6244268e153444102d14ece9"),
"title" : "MongoDB 教程",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "菜鸟教程",
"url" : "http://www.runoob.com",
"tags" : [
"mongodb",
"database",
"NoSQL",
"xxxx"
],
"likes" : 100,
"test" : "xxxx",
"xxx" : "xxxx"
}
{ "_id" : ObjectId("624427281f98d57822e9031c"), "test5" : "OK" }
>
如需插入到数组中
使用addToSet
db.col.update({ },{$set:{“addToSet”:“xxxx”}})
效果
> db.col.update({ "_id" : ObjectId("6244268e153444102d14ece9")},{$addToSet:{"tags":"addToSet"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find().pretty()
{
"_id" : ObjectId("6244268e153444102d14ece9"),
"title" : "MongoDB 教程",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "菜鸟教程",
"url" : "http://www.runoob.com",
"tags" : [
"mongodb",
"database",
"NoSQL",
"xxxx",
"addToSet"
],
"likes" : 100,
"test" : "xxxx",
"xxx" : "xxxx"
}
{ "_id" : ObjectId("624427281f98d57822e9031c"), "test5" : "OK" }
或使用push
db.col.update({ },{$push:{“xxx”:“xxxx”}})
效果
> db.col.update({ "_id" : ObjectId("6244268e153444102d14ece9")},{$push:{"tags":"push"}})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.col.find().pretty()
{
"_id" : ObjectId("6244268e153444102d14ece9"),
"title" : "MongoDB 教程",
"description" : "MongoDB 是一个 Nosql 数据库",
"by" : "菜鸟教程",
"url" : "http://www.runoob.com",
"tags" : [
"mongodb",
"database",
"NoSQL",
"xxxx",
"addToSet",
"push"
],
"likes" : 100,
"test" : "xxxx",
"xxx" : "xxxx"
}
{ "_id" : ObjectId("624427281f98d57822e9031c"), "test5" : "OK" }
添加用户
db.createUser({ user: 'testname', // 用户名 pwd: 'testpwd', // 密码 roles: [ { role: 'readWrite', // 读写权限 db: 'test' // 所属数据库 } ] })