CRUD 操作
大约 2 分钟
- 与
SQL
对应的关系
SQL | MongoDB |
---|---|
database | database |
table | collection |
row | document |
column | field |
index | index |
joins | 无表连接,使用嵌入式文档替代 |
primary key | primary key |
以下操作均是对于 document
增
db.COLLECTION_NAME.insertOne(
<document>,
{
writeConcern: <document>
}
)
db.COLLECTION_NAME.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
插入单条数据, 这里没有显式的创建 user
集合,直接执行插入语句会判断是否存在该集合,没有该集合会自动创建,插入的时候没有指定 _id
则会自动分配 ObjectId
miodb> db.user.insertOne({"name":"miomiora", "age":24, "gender":"男"})
{
acknowledged: true,
insertedId: ObjectId("641fba25e438a9958f14131a")
}
miodb> db.user.insertMany([{"name":"akiyama", "age":17, "gender":"女"},{"name":"yui", "age":16, "gender":"女"},{"name":"hanamaru", "age":19, "gender":"女"},{"name":"makoto", "age":51, "gender":"男"}])
{
acknowledged: true,
insertedIds: {
'0': ObjectId("641fbad6e438a9958f14131b"),
'1': ObjectId("641fbad6e438a9958f14131c"),
'2': ObjectId("641fbad6e438a9958f14131d"),
'3': ObjectId("641fbad6e438a9958f14131e")
}
}
查
查询语句
db.COLLECTION_NAME.find(<query>, [projection]
,其中findOne()
方法只返回一个文档
miodb> db.user.findOne()
{
_id: ObjectId("641fba25e438a9958f14131a"),
name: 'miomiora',
age: 24,
gender: '男'
}
miodb> db.user.find()
[
{
_id: ObjectId("641fba25e438a9958f14131a"),
name: 'miomiora',
age: 24,
gender: '男'
},
{
_id: ObjectId("641fbad6e438a9958f14131b"),
name: 'akiyama',
age: 17,
gender: '女'
},
{
_id: ObjectId("641fbad6e438a9958f14131c"),
name: 'yui',
age: 16,
gender: '女'
},
{
_id: ObjectId("641fbad6e438a9958f14131d"),
name: 'hanamaru',
age: 19,
gender: '女'
},
{
_id: ObjectId("641fbad6e438a9958f14131e"),
name: 'makoto',
age: 51,
gender: '男'
}
]
改
db.COLLECTION_NAME.updateOne(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>
}
)
db.COLLECTION_NAME.updateMany(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string>
}
)
把所有性别为 男
的文档改为 女
, $set
表示只替换后面的键值对
miodb> db.user.updateMany({gender:"男"}, {$set:{gender:"女"}})
{
acknowledged: true,
insertedId: null,
matchedCount: 2,
modifiedCount: 2,
upsertedCount: 0
}
删
# 此外还有 deleteMany() 方法
db.COLLECTION_NAME.deleteOne(
<filter>,
{
writeConcern: <document>,
collation: <document>,
hint: <document|string>
}
)
示例
miodb> db.user.deleteOne({gender:"女"})
{ acknowledged: true, deletedCount: 1 }