MongoDB 基础操作之新增操作

插入

MongoDB 中,可以通过插入指令将文档数据新增至集合中,最常用的为 insert()save()。除此之外,还有interOne()interMany(),不过 insert() 已涵盖这两个指令的功能。

1.1.1 insert()

此方法是插入文档最常用的方法,可以插入单笔或多笔文档。

(1) 语法格式

> db.collection.insert(

    <document or array of documents > ,

    {

        writeConcern: < document > ,

        ordered: < boolean >

    }

)
(2) 参数说明
  • document or array of documents: 要被插入的文档或数组。可以控制插入一笔或多笔文档。

    --- 当插入一笔文档时,文档内容放置在{ }中,如:{ doc }

    --- 当插入多笔文档时,单笔文档放置在 { } 中,然后将所有文档一起放置在 [ ] 中,如: [ { doc1 }, { doc2 } ]

  • writeConcern: 此为可选参数。表示是否使用写入策略。

  • ordered: 可选参数。表示插入文档时是否为有序插入。默认为 true

    --- 若为有序插入,则当插入的文档中有一个发生错误时,MongoDB 将不再继续插入后续的文档。

    --- 若为无序插入,则当插入的文档中有一个文档发生错误时,MongoDB 将会继续插入后续的文档。

(3) 范例

> db.Product.insert(

    [{

            SysNo: 2971,

            ProductName: "DE - 1300 Earbuds",

            Weight: 465,

            ProductMode: "Set"

        },

        {

            SysNo: 8622,

            ProductName: "( Role Gold) 16GB",

            Weight: 143,

            ProductMode: ""

        }

    ],

    {

        writeConcern: {
            w: "majority",
            j: true,
            wtimeout: 5000
        }, // 写入大多数节点,写入日志,限时 5000ms ordered: false

    }

)


// 执行结果
BulkWriteResult({

    "writeErrors": [],

    "writeConcernErrors": [],

    "nInserted": 2,

    "nUpserted": 0,

    "nMatched": 0,

    "nModified": 0,

    "nRemoved": 0,

    "upserted": []

})

使用find() 对集合进行查询,并且使用pretty()将结果使用更易读的方式显示出来,具体指令如下:

> db.Product.find()

// 执行结果
{ "_id" : ObjectId("60da7be26350a57504489e72"), "ProductNname" : "Rarbus", "SysNo" : 123, "Weigth" : 122, "ProductMode" : "" }

{ "_id" : ObjectId("60da83996350a57504489e73"), "SysNo" : 2971, "ProductName" : "DE - 1300 Earbuds", "Weight" : 465, "ProductMode" : "Set" }

{ "_id" : ObjectId("60da83996350a57504489e74"), "SysNo" : 8622, "ProductName" : "( Role Gold) 16GB", "Weight" : 143, "ProductMode" : "" }
 > db.Product.find().pretty()

// 执行结果
{

    "_id": ObjectId("60da7be26350a57504489e72"),

    "ProductNname": "Rarbus",

    "SysNo": 123,

    "Weigth": 122,

    "ProductMode": ""

}

{

    "_id": ObjectId("60da83996350a57504489e73"),

    "SysNo": 2971,

    "ProductName": "DE - 1300 Earbuds",

    "Weight": 465,

    "ProductMode": "Set"

}

{

    "_id": ObjectId("60da83996350a57504489e74"),

    "SysNo": 8622,

    "ProductName": "( Role Gold) 16GB",

    "Weight": 143,

    "ProductMode": ""

}
(4) 插入文档的三个特点:
  • 如果没有指定数据库,则在插入文档时会自动创建一个名为test的数据库。
  • 在插入文档时,如果没有此集合,则MongoDB会自动创建这个集合名称。
  • 在插入文档时,若没有指定_id字段,则MongiDB会自动增加一个_id字段,默认是ObjectId类型,其值在集合中是不能重复的;若指定_id字段,则其值是不能重复的,可以是数字或字符串类型。
1.1.2 save()

此方法为常用的插入方法之一,它与 insert()不同之处是:使用insert()方法插入主键相同的文档时会报错,而使用save()方法插入已存在相同主键的文档时则会覆盖原文档。

> db.Product.insert({ProductNname: "Rarbus", SysNo: 123, Weigth: 122, ProductMode:"", _id:1})
WriteResult({ "nInserted" : 1 })
> db.Product.insert({ProductNname: "Rarbus", SysNo: 123, Weigth: 122, ProductMode:"", _id:1})
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 11000,
        "errmsg" : "E11000 duplicate key error collection: test.Product index: _id_ dup key: { _id: 1.0 }"
    }
})


> db.Product.save({ProductNname: "Rarbus666", SysNo: 789, Weigth: 678, ProductMode:"", _id:3})
WriteResult({ "nMatched" : 0, "nUpserted" : 1, "nModified" : 0, "_id" : 3 })

> db.Product.save({ProductNname: "Rarbus999999", SysNo: 666666, Weigth: 888888, ProductMode:"addf", _id:3})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

> db.Product.find().pretty()
{
    "_id" : ObjectId("60da7be26350a57504489e72"),
    "ProductNname" : "Rarbus",
    "SysNo" : 123,
    "Weigth" : 122,
    "ProductMode" : ""
}
{
    "_id" : ObjectId("60da83996350a57504489e73"),
    "SysNo" : 2971,
    "ProductName" : "DE - 1300 Earbuds",
    "Weight" : 465,
    "ProductMode" : "Set"
}
{
    "_id" : ObjectId("60da83996350a57504489e74"),
    "SysNo" : 8622,
    "ProductName" : "( Role Gold) 16GB",
    "Weight" : 143,
    "ProductMode" : ""
}
{
    "_id" : 1,
    "ProductNname" : "Rarbus",
    "SysNo" : 123,
    "Weigth" : 122,
    "ProductMode" : ""
}
{
    "_id" : ObjectId("60da90d46350a57504489e75"),
    "ProductNname" : "Rarbus",
    "SysNo" : 123,
    "Weigth" : 122,
    "ProductMode" : ""
}
{
    "_id" : 2,
    "ProductNname" : "Rarbus",
    "SysNo" : 333,
    "Weigth" : 222,
    "ProductMode" : ""
}
{
    "_id" : ObjectId("60da91676350a57504489e76"),
    "ProductNname" : "Rarbus",
    "SysNo" : 123,
    "Weigth" : 122,
    "ProductMode" : ""
}
{
    "_id" : ObjectId("60da91866350a57504489e77"),
    "ProductNname" : "Rarbus",
    "SysNo" : 123,
    "Weigth" : 122,
    "ProductMode" : ""
}
{
    "_id" : 3,
    "ProductNname" : "Rarbus999999",
    "SysNo" : 666666,
    "Weigth" : 888888,
    "ProductMode" : "addf"
}
(1) 语法格式
db.collection.save(
     < document > , 
     {
       writeConcern: < document >
     }
)
(2) 范例

使用save()方法向集合中插入一个文档,指令如下:

> db.Product.save({ProductNname: "Rarbus", SysNo: 123, Weigth: 122, ProductMode:""})

WriteResult({ "nInserted" : 1 })

查看文档指令:

> db.Product.find({
    "Weigth": 88888888
}) 


{
    "_id": ObjectId("60da99fd6350a57504489e78"), // 未指定_id,则生成唯一值
    "ProductNname": "Rarbus999999999",
    "SysNo": 666666,
    "Weigth": 88888888,
    "ProductMode": "addf"
}

若保存的是_id重复的文档,则会直接覆盖此数据。此例为修改ProductMode字段值,并移除两个字段,具体指令如下:

> db.Product.save({
    "_id": ObjectId("60da99fd6350a57504489e78"),
    "Weigth": 88888888,
    "ProductMode": "Set"
})


WriteResult({
    "nMatched": 1,
    "nUpserted": 0,
    "nModified": 1
})

使用save()方法插入多条数据

> db.Product.save([{ "Weigth" : 888888881, "ProductMode" : "Set1"}, { "Weigth" : 888888882, "ProductMode" : "Set2" }])

BulkWriteResult({
    "writeErrors" : [ ],
    "writeConcernErrors" : [ ],
    "nInserted" : 2,
    "nUpserted" : 0,
    "nMatched" : 0,
    "nModified" : 0,
    "nRemoved" : 0,
    "upserted" : [ ]
})

查看文档数据:

> db.Product.find({"Weigth": 88888888}).pretty()
{
    "_id": ObjectId("60da99fd6350a57504489e78"),
    "Weigth": 88888888,
    "ProductMode": "Set"
}
3. insertOne()

同样作为插入文档的方法,insertOne()只能插入一笔文档。如果使用这个方法插入多笔文档,则MongoDB只会新增第一笔文档。

(1) 语法格式:
db.collection.insertOne(
     < document > , 
     {
       writeConcern: < document >
     }
)
(2) 范例

使用insertOne()方法插入一笔文档,指令如下:

> db.Product.insertOne({ "Weigth" : 888888883, "ProductMode" : "Set3"})

{
    "acknowledged" : true,
    "insertedId" : ObjectId("60da9f166350a57504489e7c")
}

使用insertOne()方法插入多条数据报错(系统环境:CentOS Linux release 7.9.2009 (Core)MongoDB 版本:v4.4.6改版还是指令错误???

> db.Product.insertOne([{ "Weigth" : 88888888666, "ProductMode" : "6Set6"}, { "Weigth" : 5888888885, "ProductMode" : "Set5" }])

uncaught exception: Error: operation passed in cannot be an Array :
addToOperationsList@src/mongo/shell/bulk_api.js:604:23
Bulk/this.insert@src/mongo/shell/bulk_api.js:650:20
DBCollection.prototype.insertOne@src/mongo/shell/crud_api.js:260:5
@(shell):1:1
4. insertMany()

insertMany()可以插入多个文档,插入方法与insert()方法相同。

(1) 语法格式:
db.collection.insertMany(
    [ < document1 > , < document2 > , ...], 
        {

        writeConcern: < document > ,

        ordered: < boolean >

    }
)
(2) 范例
> db.Product.insertMany([{ "Weigth" : 88888888666, "ProductMode" : "6Set6"}, { "Weigth" : 5888888885, "ProductMode" : "Set5" }])

{
    "acknowledged" : true,
    "insertedIds" : [
        ObjectId("60daa7b1063796028af0b87c"),
        ObjectId("60daa7b1063796028af0b87d")
    ]
}

使用insertMany()方法插入单条文档时报错(系统环境:CentOS Linux release 7.9.2009 (Core)MongoDB 版本:v4.4.6

> db.Product.insertMany({ "Weigth" : 8888888866677777, "ProductMode" : "6Set67799999999777"})

uncaught exception: TypeError: documents.map is not a function :
DBCollection.prototype.insertMany@src/mongo/shell/crud_api.js:307:17
@(shell):1:1
摘抄于《MoongoDB 从入门到商业实战》
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容