How do I insert many objects to a List In C# MongoDB.Driver

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

my c# Entity

       /// <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; }

        }

In the MongoDBCode Like the code

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

i will add objects to the “VisitInfos”:
How do i insert Adds many objects to the the List In c# MongoDB.Driver

The Way 1 : insert ony one object my test code is

 

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);

The Way 2 : i want to insert 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);


                      
                }

the way 2 is failed

pls help me

ths very much…

Have you looked at how $push with $each modifier works?

https://docs.mongodb.com/manual/reference/operator/update/each

3 Likes

OK …i will …look it ths