0

如何在 c# MongoDB.Driver 中插入将许多对象添加到列表中?

我的 C# 实体

       /// <summary>LogTest</summary>
        public class VisitLog
        {
            /// <summary>MongoDB特有的字段&lt;/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失败。

请帮我。这个非常……

4

1 回答 1

0

在上面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"
                }
        ]
}
于 2020-09-03T08:57:45.343 回答