简体   繁体   中英

How to insert data in mongodb array using C#.Net?

I have collection of Veh_info in mongodb having

id:1
color:red
Cly:4
Loc:{ Loc1
      Loc2
    }

I have created classes like

public class Car()
{ Public Objectid id {get;set;}
  public color {get;set;}
  public  Cly {get;set;}
  Public Location loc {get;set}
}
Public class Location()
{ public string loc{get;set;}
}

I have no idea how to insert new record ie Loc3 in array in C# on Click event . If any one give some hits.thanks

so, collection Veh_info==Car? if is that true, why Location type property in Car class is not array? You have errors in your class definition.

public class Car
{
   public ObjectId Id{get;set;}
   public string Color{get;set;}
   public int Cly{get;set;}
   public List<Location>Locs{get;set;}
}  

than you can use this code:

MongoDB.Driver.MongoClient client = new MongoClient(connectionString);
var server = client.GetServer();
var db = server.GetDatabase("MyDbName");
var collection=db.GetCollection<Car>("Veh_info");
Car carById= collection.Find(Query<Car>.EQ(x=>x.Id,1));
if(carById!=null)
  carById.Locs.Add(new Location(){loc="my new location name"});
collection.Save(carById);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM