新增单行
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() 将单个文档或多个文档插入集合中。 |