MongoDB-新增文档

10 篇文章 0 订阅
1 篇文章 0 订阅

新增文档

3.2版本以以上可用

IMongoCollection.InsertOne() 新增一个 document 到 Collection.

以下演示新增行到inventory表中,如果行不指定_id字段,C#驱动会为行增加_id字段,查看插入动作

var document = new BsonDocument
{
    { "item", "canvas" },
    { "qty", 100 },
    { "tags", new BsonArray { "cotton" } },
    { "size", new BsonDocument { { "h", 28 }, { "w", 35.5 }, { "uom", "cm" } } }
};
collection.InsertOne(document);

若要检索刚才插入的文档,请查询集合:

var filter = Builders<BsonDocument>.Filter.Eq("item", "canvas");
var result = collection.Find(filter).ToList();

批量新增

新版本3.2。
可以将多个记录插入到集合中。将可枚举的记录集合传递给方法。
下面的示例将三个新记录插入到inventory 表中。如果文档没有指定一个_id字段,则驱动程序将Object ID值添加到每行中。参见插入行为。

var documents = new BsonDocument[]
{
    new BsonDocument
    {
        { "item", "journal" },
        { "qty", 25 },
        { "tags", new BsonArray { "blank", "red" } },
        { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, {  "uom", "cm"} } }
    },
    new BsonDocument
    {
        { "item", "mat" },
        { "qty", 85 },
        { "tags", new BsonArray { "gray" } },
        { "size", new BsonDocument { { "h", 27.9 }, { "w", 35.5 }, {  "uom", "cm"} } }
    },
    new BsonDocument
    {
        { "item", "mousepad" },
        { "qty", 25 },
        { "tags", new BsonArray { "gel", "blue" } },
        { "size", new BsonDocument { { "h", 19 }, { "w", 22.85 }, {  "uom", "cm"} } }
    },
};
collection.InsertMany(documents);

新增方法

MunGDB提供了将文档插入到集合中的以下方法:

db.collection.insertOne()将单个文档插入到集合中。
db.collection.insertMany()db.collection.insertMany() 将多个文档插入到集合中。
db.collection.insert()db.collection.insert() 将单个文档或多个文档插入集合中。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值