mongodb crud – create
1. db.collection.insert()
- 语法
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
- 参数说明
参数 | 类型 | 说明 |
---|---|---|
document or array of documents | document or array | 单个文档或这包含多个文档的数组 |
writeConcern | document | 可选参数,文档形式:{ w: value, j: boolean, wtimeout: number },默认:{w:1, j:true}。wtimeout参数只在w参数的值大于1才有效,防止集群大多数节点失效的情况下写操作无限期阻塞,单位毫秒,超时后返回错误,但是不会撤销已经成功写入的数据。 |
ordered | boolean | 可选参数,默认ture。如果值为true,顺序插入数组文档,发生错误,立即停止后续插入;如果值为false,插入过程发生错误,会继续执行插入 |
+ 其他插入方法
# New in version 3.2
db.inventory.insertOne(
{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }
)
# New in version 3.2
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } },
{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } },
{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }
])
2. db.collection.save()
- 语法
db.collection.save(
<document>,
{
writeConcern: <document>
}
)
如果文档中没有_id字段,save操作调用insert方法,如果文档包含_id字段,save操作调用update操作,更新的查询条件是_id,并且upsert选项的值是true。
- 参数说明
参数 | 类型 | 说明 |
---|---|---|
document | document | 单个文档 |
writeConcern | document | 可选参数,文档形式:{ w: value, j: boolean, wtimeout: number },默认:{w:1, j:true}。wtimeout参数只在w参数的值大于1才有效,防止集群大多数节点失效的情况下写操作无限期阻塞,单位毫秒,超时后返回错误,但是不会撤销已经成功写入的数据。 |
3. db.collection.update(query, update, options)
- 语法
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
- 参数说明
参数 | 类型 | 说明 |
---|---|---|
query | document | 更新的查询条件 |
update | document | 更新的操作,使用操作符。如果没有操作符,可能会将文档整个替换,但是_id字段不会被替换 |
upsert | boolean | 可选参数,默认false。当值为true,如果没有查询到匹配文档,会插入新的文档 |
multi | boolean | 可选参数,默认false。当值为true,更新所有查询匹配的文档,否则只更新一个文档 |
writeConcern | document | 可选参数,文档形式:{ w: value, j: boolean, wtimeout: number },默认:{w:1, j:true}。wtimeout参数只在w参数的值大于1才有效,防止集群大多数节点失效的情况下写操作无限期阻塞,单位毫秒,超时后返回错误,但是不会撤销已经成功写入的数据。 |
+ 注意
To avoid inserting the same document more than once, only use upsert: true if the query field is uniquely indexed.
4. db.collection.findAndModify()
db.collection.findAndModify({
query: <document>,
sort: <document>,
remove: <boolean>,
update: <document>,
new: <boolean>,
fields: <document>,
upsert: <boolean>,
bypassDocumentValidation: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
})
默认只修改第一个文档并返回该文档,如果要返回修改后的文档,需设置new参数为true(默认false)