識搵野唔識入野都無用, MongoDB 入野, 有幾個方法:
- db.collection.insert()
- db.collection.insertOne()
- db.collection.insertMany()
db.collection.insert(
<document or array of documents>,
{
writeConcern: <document>,
ordered: <boolean>
}
)
可以用黎加一份 document (可以睇成係一隻 JSON record), 或者成個 array 既 documents
例如:
- db.sample.insert({user:"Super169"})
- db.sample.insert([{user:"Super167"},{user:"Super168"},{user:"Super169"}])
db.collection.insertOne(
<document>,
{
writeConcern: <document>
}
)
唔駛多講, 只可以 insert 一份 document, 唔可以成個 array 比佢.
例如:
- db.sample.insertOne({user:"Super169"})
db.collection.insertMany(
[ <document 1> , <document 2>, ... ],
{
writeConcern: <document>,
ordered: <boolean>
}
)
同 insertOne 對著幹, 只可以成個 array 比佢, 唔可以單獨一份 document.
不過, 個 array 入面可以只係得一份 document....甚至無野.
例如:
- db.sample.insertMany([{user:"Super167"},{user:"Super168"},{user:"Super169"}])
insert, insertOne 同 insertMany 有乜分別?
無事無幹, 對個 collection 而言, 係無分別既, 你可以用哂 insert 唔駛煩.
不過, 佢地既 return object 就有 D 唔同, 你要做 error handling, 就要識分.
例如:
- db.sample.insert({user:"Super169"})
WriteResult({ "nInserted" : 1 })
- db.sample.insertOne({user:"Super169"})
{ "acknowledged" : true, "insertedId" : ObjectId("5901a950276033a2cfe79009")}
- db.sample.insert([{user:"Super167"},{user:"Super168"},{user:"Super169"}])
BulkWriteResult({
"writeErrors" : [ ],
"writeConcernErrors" : [ ],
"nInserted" : 3,
"nUpserted" : 0,
"nMatched" : 0,
"nModified" : 0,
"nRemoved" : 0,
"upserted" : [ ]
})
- db.sample.insertMany([{user:"Super167"},{user:"Super168"},{user:"Super169"}])
{
"acknowledged" : true,
"insertedIds" : [
ObjectId("5901a9e9276033a2cfe7900d"),
ObjectId("5901a9e9276033a2cfe7900e"),
ObjectId("5901a9e9276033a2cfe7900f")
]
}
至於用邊個, 睇下你自己想點了. insert 完想攞番個 key 去再做野, 就用 insertOne 或者 insertMany, 否則, insert 完知道得唔得就夠, 用 insert 就可以了.