Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

mongodb - What's the difference between insert(), insertOne(), and insertMany() method?

What's the difference between insert(), insertOne(), and insertMany() methods on MongoDB. In what situation should I use each one?

I read the docs, but it's not clear when use each one.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

What's the difference between insert(), insertOne() and insertMany() methods on MongoDB

  • db.collection.insert() as mentioned in the documentation inserts a document or documents into a collection and returns a WriteResult object for single inserts and a BulkWriteResult object for bulk inserts.

    > var d = db.collection.insert({"b": 3})
    > d
    WriteResult({ "nInserted" : 1 })
    > var d2 = db.collection.insert([{"b": 3}, {'c': 4}])
    > d2
    BulkWriteResult({
            "writeErrors" : [ ],
            "writeConcernErrors" : [ ],
            "nInserted" : 2,
            "nUpserted" : 0,
            "nMatched" : 0,
            "nModified" : 0,
            "nRemoved" : 0,
            "upserted" : [ ]
    })
    
  • db.collection.insertOne() as mentioned in the documentation inserts a document into a collection and returns a document which look like this:

    > var document = db.collection.insertOne({"a": 3})
    > document
    {
            "acknowledged" : true,
            "insertedId" : ObjectId("571a218011a82a1d94c02333")
    }
    
  • db.collection.insertMany() inserts multiple documents into a collection and returns a document that looks like this:

    > var res = db.collection.insertMany([{"b": 3}, {'c': 4}])
    > res
    {
            "acknowledged" : true,
            "insertedIds" : [
                    ObjectId("571a22a911a82a1d94c02337"),
                    ObjectId("571a22a911a82a1d94c02338")
            ]
    }
    

In what situation should I use each one?

The insert() method is deprecated in major driver so you should use the the .insertOne() method whenever you want to insert a single document into your collection and the .insertMany when you want to insert multiple documents into your collection. Of course this is not mentioned in the documentation but the fact is that nobody really writes an application in the shell. The same thing applies to updateOne, updateMany, deleteOne, deleteMany, findOneAndDelete, findOneAndUpdate and findOneAndReplace. See Write Operations Overview.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...