我如何插入将许多对象添加到 C# 中的列表 MongoDB.Driver

How do i insert Adds many objects to the the List In c# MongoDB.Driver

如何在 c# 中将多个对象插入列表 MongoDB.Driver?

我的 c# 实体

       /// <summary>LogTest</summary>
        public class VisitLog
        {
            /// <summary>MongoDB特有的字段</summary>
            [MongoDB.Bson.Serialization.Attributes.BsonElement("_id")]
            [JsonConverter(typeof(ObjectIdConverter))]
            public MongoDB.Bson.ObjectId MongoId { get; set; }

            /// <summary>YMD datetime</summary>
            public int Yymmdd { get; set; }

            /// <summary>Visitor</summary>
            public string Visitor { get; set; }

            /// <summary>VisitInfos</summary>
            public List<VisitInfo> VisitInfos { get; set; }

        }

在MongoDBCode中点赞代码

// 1
{
    "_id": ObjectId("5f506eb02000a9b52d72a600"),
    "Yymmdd": NumberInt("20200903"),
    "Visitor": "360spider",
    "VisitInfos": [ ]
}

我会将对象添加到“VisitInfos”:[ ]

如何在 c# 中将多个对象插入列表 MongoDB.Driver?

方式一:只插入一个对象。我的测试代码是:

 

var filter = Builders<VisitLog>.Filter.Eq("_id", item.MongoId);
var update = Builders<VisitLog>.Update.Push("VisitInfos", new VisitInfo { Visitor = Visitor, Browser = "IE", Ip = "192.168.1.1", Createtime = DateTime.Now.ToUnixTimeLocalIslong() });
var result = BB.UpdateOne(filter, update);

方法 2:我想插入 InsertManyAsync

var items = BB.Find(x => x.Yymmdd.Equals(Yymmdd) && x.Visitor.Equals(Visitor)).Project<VisitLog>(fields).ToList();
                if (items.Count > 0)
                {
                    var item = items[0];


                    var VisitInfos = new List<VisitInfo>();

                    for (int j = 0; j < 10000; j++)
                    {
                        VisitInfos.Add(new VisitInfo { Visitor = Visitor, Browser = "IE", Ip = "192.168.1.1", Createtime = DateTime.Now.ToUnixTimeLocalIslong() });
                    }

                    var filter = Builders<VisitLog>.Filter.Eq("_id", item.MongoId);
                    var update = Builders<VisitLog>.Update.Push("VisitInfos", VisitInfos);
                    var result = BB.UpdateOne(filter, update);
  
                }

方式2失败

请帮助我。 这个非常.....

Builders<Order>.Update 上有一个 PushEach 接受 IEnumerable。这相当于做:

{ $push: { scores: { $each: [ 90, 92, 85 ] } } }

https://docs.mongodb.com/manual/reference/operator/update/push/#append-multiple-values-to-an-array

为简单起见,这里有一个订单和订单商品的示例。

在 MongoDB 中我们将有:

> db.orders.find()
{ "_id" : ObjectId("5f50aef4d7d9f967d0322932"), "Items" : [ ] }

然后我们将执行以下 C# 代码。

var client = new MongoClient();
var db = client.GetDatabase("test");
var items = db.GetCollection<Order>("orders");

var filter = Builders<Order>.Filter.Empty;
var update = Builders<Order>.Update.PushEach(x => x.Items, new[]
{
    new OrderItem{Name = "Order 1", Price = 10.1M},
    new OrderItem{Name = "Order 2", Price = 20.2M}
});

await items.UpdateOneAsync(filter, update);
public class Order
{
    public ObjectId Id { get; set; }
    
    public List<OrderItem> Items { get; set; } 
        = new List<OrderItem>();

}

public class OrderItem
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

现在,如果我们查看 MongoDB 中的文档,我们会将 2 项添加到我们的数组中

 db.orders.find().pretty()
{
        "_id" : ObjectId("5f50aef4d7d9f967d0322932"),
        "Items" : [
                {
                        "Name" : "Order 1",
                        "Price" : "10.1"
                },
                {
                        "Name" : "Order 2",
                        "Price" : "20.2"
                }
        ]
}