public void Crear(Pedido pedido) { try { baseDatos.GetCollection <Pedido>(nameof(Pedido)).InsertOne(pedido); } catch (Exception ex) { throw new Exception($"{nameof(Crear)} no fue posible guardar el pedido en base de datos {ex.ToString()}"); } }
// POST api/<controller> public AddMemberResponse Post(AddMemberRequest request) { var response = new AddMemberResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var memberCollection = db.GetCollection <MemberCollection>("members"); var query = Builders <MemberCollection> .Filter.Eq(e => e.uid, request.uid); var doc = memberCollection.Find(query).ToListAsync().Result.FirstOrDefault(); if (doc == null) { memberCollection.InsertOne(new MemberCollection() { _id = ObjectId.GenerateNewId(), uid = request.uid, name = request.name, phone = request.phone }); } else { response.ok = false; response.errMsg = $"Number: {request.uid} is exist"; } return(response); }
// PUT api/<controller>/5 public EditMemberResponse Put(EditMemberRequest request) { var response = new EditMemberResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var memberCollection = db.GetCollection <MemberCollection>("members"); var query = Builders <MemberCollection> .Filter.Eq(e => e.uid, request.uid); var doc = memberCollection.Find(query).ToListAsync().Result.FirstOrDefault(); if (doc != null) { var update = Builders <MemberCollection> .Update.Set("name", request.name).Set("phone", request.phone); memberCollection.UpdateOne(query, update); //memberCollection.InsertOne(new MemberCollection() //{ // _id = ObjectId.GenerateNewId(), // uid = request.uid, // name = request.name, // phone = request.phone //}); } else { response.ok = false; response.errMsg = $"Number: {request.uid} is update fail"; } return(response); }
public GetMemberListResponse Get() { /* 宣告指令的輸出結果 */ var response = new GetMemberListResponse(); /* Step1 連接MongoDB伺服器 */ MongoClient client = new MongoClient("mongodb://localhost:27017"); /* Step2 取得MongoDB資料庫(Database)和集合(Collection) */ /* Step2-1 取得ntut資料庫(Database) */ MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; /* Step2-2 取得members集合(Collection) */ var membersCollection = db.GetCollection <MembersCollection>("members"); /* Step3 取得全部會員的資訊 */ /* Step3-1 設定空的查詢式,即查詢全部的資料 */ var query = new BsonDocument(); /* Step3-2 進行查詢的操作,並取得結果集合 */ var cursor = membersCollection.Find(query).ToListAsync().Result; /* Step4設定指令的輸出結果 */ foreach (var doc in cursor) { response.list.Add( new MemberInfo() { uid = doc.uid, name = doc.name, phone = doc.phone } ); } return(response); }
public DeletMemberResponse Delete(string id) { /* 宣告指令的輸出結果 */ var response = new DeletMemberResponse(); /* Step1 連接MongoDB伺服器 */ MongoClient client = new MongoClient("mongodb://localhost:27017"); /* Step2 取得MongoDB資料庫(Database)和集合(Collection) */ /* Step2-1 取得ntut資料庫(Database) */ MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; /* Step2-2 取得members集合(Collection) */ var membersCollection = db.GetCollection <MembersCollection>("members"); /* Step3 刪除會員資訊 */ /* Step3-1 設定查詢式 */ var query = Builders <MembersCollection> .Filter.Eq(e => e.uid, id); /* Step3-2 進行刪除會員資訊的操作 */ var result = membersCollection.DeleteOne(query); if (result.DeletedCount != 0) { /* Step3-3-1 當刪除會員資訊成功時,直接回傳response */ return(response); } else { /* Step3-3-2 當刪除會員資訊失敗時,設定Response的ok欄位與errMsg欄位 */ response.ok = false; response.errMsg = "編號為" + id + "的會員不存在,請確認會員編號。"; return(response); } }
public PessoaMongoDB() { var cliente = new MongoClient(StringConexao); DataBase = (MongoDatabaseBase)cliente.GetDatabase(DataBaseName); Pessoas = DataBase.GetCollection <Pessoa>(DataBaseName); }
/// <summary> /// 取得全部會員 /// </summary> /// <returns></returns> public GetMemberListResponse Get() { var response = new GetMemberListResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = (MongoDatabaseBase)client.GetDatabase("ntut"); var membersCollection = db.GetCollection <MembersCollection>("members"); //空的查詢式 var query = new BsonDocument(); //查詢並取得結果 var cursor = membersCollection.Find(query).ToListAsync().Result; foreach (var doc in cursor) { response.list.Add( new MemberInfo() { uid = doc.uid, name = doc.name, phone = doc.phone } ); } return(response); }
public GetMemberResponse Get(string id) { /* 宣告指令的輸出結果 */ var response = new GetMemberResponse(); /* Step1 連接MongoDB伺服器 */ MongoClient client = new MongoClient("mongodb://localhost:27017"); /* Step2 取得MongoDB資料庫(Database)和集合(Collection) */ /* Step2-1 取得ntut資料庫(Database) */ MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; /* Step2-2 取得members 集合(Collection) */ var colMembers = db.GetCollection <MembersDocument>("members"); /* Step3 取得指定會員的資訊 */ /* Step3-1 設定查詢式 */ var query = Builders <MembersDocument> .Filter.Eq(e => e.uid, id); /* Step3-2 進行查詢的操作,並取得會員資訊 */ var doc = colMembers.Find(query).ToListAsync().Result.FirstOrDefault(); /* Step4 設定指令的輸出結果 */ if (doc != null) { /* Step4-1 當資料庫中存在該會員時,設定Response的data欄位 */ response.data.uid = doc.uid; response.data.name = doc.name; response.data.phone = doc.phone; } else { /* Step4-2 當資料庫中沒有該會員時,設定Response 的ok 欄位與errMsg 欄位 */ response.ok = false; response.errMsg = "沒有此會員"; } return(response); }
/// <summary> /// 取得指定會員 /// </summary> /// <param name="id"></param> /// <returns></returns> public GetMemberInfoResponse Get(string id) { var response = new GetMemberInfoResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = (MongoDatabaseBase)client.GetDatabase("ntut"); var membersCollection = db.GetCollection <MembersCollection>("members"); var query = Builders <MembersCollection> .Filter.Eq(e => e.uid, id); var doc = membersCollection.Find(query).ToListAsync().Result.FirstOrDefault(); if (doc != null) { response.data.uid = doc.uid; response.data.name = doc.name; response.data.phone = doc.phone; } else { response.ok = false; response.errMsg = "編號:" + id + "的會員不存在。"; } return(response); }
/// <summary> /// 編輯會員 /// </summary> /// <param name="request"></param> /// <returns></returns> public EditMemberResponse Put(EditMemberRequest request) { var response = new EditMemberResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = (MongoDatabaseBase)client.GetDatabase("ntut"); var membersCollection = db.GetCollection <MembersCollection>("members"); var query = Builders <MembersCollection> .Filter.Eq(e => e.uid, request.uid); var doc = membersCollection.Find(query).ToListAsync().Result.FirstOrDefault(); if (doc != null) { var update = Builders <MembersCollection> .Update .Set("name", request.name) .Set("phone", request.phone); membersCollection.UpdateOne(query, update); } else { response.ok = false; response.errMsg = "編號:" + request.uid + "的會員不存在。"; } return(response); }
public static void SeletctDbWithQueries(MongoDatabaseBase db) { var collection = db.GetCollection <BsonDocument>("testCollection"); var filter = Builders <BsonDocument> .Filter.Eq("status", "D"); var result = collection.Find(filter).ToList(); foreach (var doc in result) { Console.WriteLine(doc.ToJson()); } var filter2 = Builders <BsonDocument> .Filter.Eq("size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } }); var result2 = collection.Find(filter2).ToList(); foreach (var doc in result2) { Console.WriteLine(doc.ToJson()); } var filter3 = Builders <BsonDocument> .Filter.Eq("size.uom", "in"); var result3 = collection.Find(filter).ToList(); foreach (var doc in result3) { Console.WriteLine(doc.ToJson()); } }
public GetMemberlnfoResponse Lookup() { var response = new GetMemberlnfoResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var salesCollection = db.GetCollection <SalesCollection>("sales"); var ordersCollection = db.GetCollection <OrderCollection>("orders"); var query = Builders <SalesCollection> .Filter.Empty; var lookup = salesCollection.Aggregate() .Match(query) .Lookup( foreignCollection: ordersCollection, localField: e => e._id, foreignField: p => p.pid, @as: (SaleWithOrders eo) => eo.orders) .ToList(); return(response); }
static public void testcommand() { string connectionStr = "mongodb://localhost:27017"; MongoClient _client = new MongoClient(connectionStr); MongoDatabaseBase _database = _client.GetDatabase("music") as MongoDatabaseBase; IMongoCollection <BsonDocument> collection = _database.GetCollection <BsonDocument>("namespaces"); var s = _database.ListCollections().ToList().Count; //var value= collection.Find(new BsonDocument("", "")).First(); //int num = _database.RunCommand(new JsonCommand<int>("{db:'stats'}")); }
public static void InsertDb(MongoDatabaseBase db) { //database.CreateCollection("testCollection"); var collection = db.GetCollection <BsonDocument>("testCollection"); var documents = new[] { new BsonDocument { { "item", "journal" }, { "qty", 25 }, { "size", new BsonDocument { { "h", 14 }, { "w", 21 }, { "uom", "cm" } } }, { "status", "A" } }, new BsonDocument { { "item", "notebook" }, { "qty", 50 }, { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } }, { "status", "A" } }, new BsonDocument { { "item", "paper" }, { "qty", 100 }, { "size", new BsonDocument { { "h", 8.5 }, { "w", 11 }, { "uom", "in" } } }, { "status", "D" } }, new BsonDocument { { "item", "planner" }, { "qty", 75 }, { "size", new BsonDocument { { "h", 22.85 }, { "w", 30 }, { "uom", "cm" } } }, { "status", "D" } }, new BsonDocument { { "item", "postcard" }, { "qty", 45 }, { "size", new BsonDocument { { "h", 10 }, { "w", 15.25 }, { "uom", "cm" } } }, { "status", "A" } }, }; collection.InsertMany(documents); }
//private IMongoDatabase _mongoDatabase; public MongoDbContext(MongoClient mongoClient) { MongoDatabaseBase _mongoDatabase = (ControllersUtils.GetDatabase(mongoClient)) as MongoDatabaseBase; Conexoes = (_mongoDatabase.GetCollection <Conexao>("Conexao")) as MongoCollectionBase <Conexao>; Contatos = (_mongoDatabase.GetCollection <Contato>("Contato")) as MongoCollectionBase <Contato>; Passos = (_mongoDatabase.GetCollection <Passo>("Passo")) as MongoCollectionBase <Passo>; Scripts = (_mongoDatabase.GetCollection <Script>("Script")) as MongoCollectionBase <Script>; Campos = (_mongoDatabase.GetCollection <Campo>("Campo")) as MongoCollectionBase <Campo>; ScriptGerados = (_mongoDatabase.GetCollection <ScriptGerado>("ScriptGerado")) as MongoCollectionBase <ScriptGerado>; PassoGerados = (_mongoDatabase.GetCollection <PassoGerado>("PassoGerado")) as MongoCollectionBase <PassoGerado>; Ifxerrors = (_mongoDatabase.GetCollection <IfxError>("IfxError")) as MongoCollectionBase <IfxError>; }
public static void SelectDb(MongoDatabaseBase db) { var collection = db.GetCollection <BsonDocument>("testCollection"); var filter = Builders <BsonDocument> .Filter.Empty; var result = collection.Find(filter).ToList(); foreach (var doc in result) { Console.WriteLine(doc.ToJson()); } }
public AddMemberResponse Post(AddMemberRequest request) { var response = new AddMemberResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var merberscontroller = db.GetCollection <MembersCollection>("members"); var uids = request.members.Select(e => e.uid).ToList(); var query = Builders <MembersCollection> .Filter.In(e => e.Uid, uids); var doc = merberscontroller.Find(query).ToList(); #region 移除存在在資料庫的會員 if (doc.Count > 0) { var existUIDList = doc.Select(e => e.Uid).ToList(); request.members.RemoveAll(e => existUIDList.Contains(e.uid)); response.ok = false; var existUid = string.Join(",", existUIDList); response.errMsg = "編號為" + existUid + "的會員存在,請重新輸入別組會員編號。"; if (request.members.Count() > 0) { var membersDocs = request.members.Select(e => { return(new MembersCollection() { _id = new ObjectId(), Uid = e.uid, Phone = e.phone, Name = e.name }); }).ToList(); merberscontroller.InsertMany(membersDocs); } } #endregion else { var membersDocs = request.members.Select(e => { return(new MembersCollection() { _id = new ObjectId(), Uid = e.uid, Phone = e.phone, Name = e.name }); }).ToList(); merberscontroller.InsertMany(membersDocs); } return(response); }
static void testskip() { string connectionStr = "mongodb://localhost:27017"; MongoClient _client = new MongoClient(connectionStr); MongoDatabaseBase _database = _client.GetDatabase("FileServer") as MongoDatabaseBase; var cc = _database.GetCollection <BsonDocument>("SercherIndex"); cc.AsQueryable().ToList().ForEach(x => Console.WriteLine(x.ToJson())); Console.WriteLine("\r\n"); Console.WriteLine("\r\n"); Console.WriteLine("\r\n"); var findFluent = cc.Find(new BsonDocument("_id", new BsonDocument("$exists", true))); Console.WriteLine("\r\nlimit(1):\r\n" + findFluent.Limit(1).ToList().ToJson()); findFluent.Skip(1);//=========>result: it's will move just in first!! Console.WriteLine("\r\nSkip(1) then limit(1):\r\n" + findFluent.Limit(1).ToList().ToJson()); Console.WriteLine("\r\n ones anagin then limit(1):\r\n" + findFluent.Limit(1).ToList().ToJson()); //test skip if not move cur=========>result:NOT findFluent.Skip(1); findFluent.Skip(1); Console.WriteLine("\r\nSkip(1)*2 then limit(1):\r\n" + findFluent.Limit(1).ToList().ToJson()); //test skip if move cur=========>result:NOT findFluent.Skip(1); findFluent = findFluent.Skip(1); Console.WriteLine("\r\ncoutiue Skip(1) and limit\r\n" + findFluent.Limit(1).ToList().ToJson()); //test Cursor next //var cur = findFluent.ToCursor(); var cur = cc.Find(new BsonDocument("_id", new BsonDocument("$exists", true))).Skip(1).Limit(1).ToCursor(); do { Console.WriteLine("\r\nCursor\r\n" + cur.MoveNext().ToJson() + ":" + cur.Current.ToJson()); }while (cur.MoveNext()); //test ToEnumerable var ff = cc.Find(new BsonDocument("_id", new BsonDocument("$exists", true))).Skip(1).Limit(1); Console.WriteLine("\r\nToEnumerable\r\n" + ff.ToEnumerable().ToList().ToJson()); Console.WriteLine("\r\nToEnumerable\r\n" + ff.ToEnumerable().ToList().ToJson()); Console.ReadKey(); ///remark:IFindFluent.skip在命令中的确只有一次调用机会。。。 ///eg:IFindFluent.skip(1).skip(1)在命令中是只执行最后一个,游标只固定最后一个 ///并且调用完skip的游标会进行迭代,且会继续使用相同的limit配置 ///这点在使用IFindFluent.ToEnumerable使倒是挺合理的,针对选择进行列表化 }
public GetMemberlnfoResponse Group(string id) { var response = new GetMemberlnfoResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var memberCollection = db.GetCollection <MembersCollection>("members"); var query = Builders <MembersCollection> .Filter.Empty; var nameList = memberCollection.Aggregate().Match(query).Group(e => e.Name, e => new { Name = e.Key, Count = e.Count() }).ToList(); if (nameList.Any(e => e.Count > 1)) { response.ok = false; response.errMsg = "有會員名字重複"; } return(response); }
private void button1_Click(object sender, EventArgs e) { string connectionString = "mongodb://localhost/?safe=true"; var client = new MongoClient(connectionString); MongoDatabaseBase database = (MongoDatabaseBase)client.GetDatabase("foo"); var collection = database.GetCollection <BankInformation>("bank"); for (int i = 0; i < 500000; i++) { var document = new BankInformation(); document.BranchName = "Branchname" + i.ToString(); document.AccountNumber = i.ToString(); document.BranchCity = "Branch City " + i.ToString(); document.BankName = "Bank name" + i.ToString(); collection.InsertOne(document); } }
/// <summary> /// 刪除會員 /// </summary> /// <param name="id"></param> /// <returns></returns> public DeleteMemberResponse Delete(string id) { var response = new DeleteMemberResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = (MongoDatabaseBase)client.GetDatabase("ntut"); var membersCollection = db.GetCollection <MembersCollection>("members"); var query = Builders <MembersCollection> .Filter.Eq(e => e.uid, id); var result = membersCollection.DeleteOne(query); if (result.DeletedCount == 0) { response.ok = false; response.errMsg = "編號:" + id + "的會員不存在。"; } return(response); }
public AddMemberResponse Post(AddMemberRequest request) { /* 宣告指令的輸出結果 */ var response = new AddMemberResponse(); /* Step1 連接MongoDB伺服器 */ MongoClient client = new MongoClient("mongodb://localhost:27017"); /* Step2 取得MongoDB資料庫(Database)和集合(Collection) */ /* Step2-1 取得ntut資料庫(Database) */ MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; /* Step2-2 取得members集合(Collection) */ var membersCollection = db.GetCollection <MembersCollection>("members"); /* Step3 新增ㄧ筆會員資訊 */ /* Step3-1 設定查詢式 */ var query = Builders <MembersCollection> .Filter.Eq(e => e.uid, request.uid); /* Step3-2 進行查詢的操作,並取得會員資訊 */ var doc = membersCollection.Find(query).ToListAsync().Result.FirstOrDefault(); if (doc == null) { /* Step3-3-1 當資料庫中沒有該會員時,進行新增會員資訊的操作 */ membersCollection.InsertOne(new MembersCollection() { _id = ObjectId.GenerateNewId(), uid = request.uid, name = request.name, phone = request.phone }); } else { /* Step3-3-2 當資料庫中存在該會員時,設定Response的ok欄位與errMsg欄位 */ response.ok = false; response.errMsg = "編號為" + request.uid + "的會員已存在,請重新輸入別組會員編號。"; } return(response); }
public DeleteMemberResponse Delete(DeleteMemberRequest request) { var response = new DeleteMemberResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var memberCollection = db.GetCollection <MembersCollection>("members"); var query = Builders <MembersCollection> .Filter.In(e => e.Uid, request.uids); var existDoc = memberCollection.Find(query).ToList(); var existIds = existDoc.Select(e => e.Uid).ToList(); var result = memberCollection.DeleteMany(query); if (result.DeletedCount != request.uids.Count) { request.uids.RemoveAll(e => existIds.Contains(e)); var notExistUids = string.Join(",", request.uids); response.ok = false; response.errMsg = "編號為" + notExistUids + "的會員不存在,請確認會員編號。"; } return(response); }
public Response Sales(Request request) { var response = new Response(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var salesCollection = db.GetCollection <SalesCollection>("sales"); var query = Builders <SalesCollection> .Filter. var result = salesCollection.Aggregate().Match(query) .Group(e => e.items, g => new sales { _id = g.Key, totalSaleAmount = g.Sum(x => x.price * x.quantity), averageQuantity = g.Avg(x => x.quantity), count = g.Count() }).Tolist(); return(response); }
// DELETE api/<controller>/5 public DeleteMemberResponse Delete(string id) { var response = new DeleteMemberResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var memberCollection = db.GetCollection <MemberCollection>("members"); var query = Builders <MemberCollection> .Filter.Eq(e => e.uid, id); var result = memberCollection.DeleteOne(query); if (result.DeletedCount != 0) { } else { response.ok = false; response.errMsg = $"Number: {id} Delete fail"; } return(response); }
protected override void Execute(CodeActivityContext context) { var database_name = DB_Name.Get(context); var coll_name = Collection_Name.Get(context); var database_ip = DB_Server_IP.Get(context); //Connects to the Server MongoClient mongoclient = new MongoClient(database_ip); //List of all the Databases //Connects to the Existing Database MongoDatabaseBase myDB = (MongoDatabaseBase)mongoclient.GetDatabase(database_name); var coll_list = myDB.ListCollectionNames().ToList(); if (coll_list.Contains(coll_name)) { var coll = myDB.GetCollection <BsonDocument>(coll_name); } else { myDB.CreateCollection(coll_name); } }
public EditMemberResponse Put(EditMemberRequest request) { /* 宣告指令的輸出結果 */ var response = new EditMemberResponse(); /* Step1 連接MongoDB伺服器 */ MongoClient client = new MongoClient("mongodb://localhost:27017"); /* Step2 取得MongoDB資料庫(Database)和集合(Collection) */ /* Step2-1 取得ntut資料庫(Database) */ MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; /* Step2-2 取得members集合(Collection) */ var membersCollection = db.GetCollection <MembersCollection>("members"); /* Step3 修改會員資訊 */ /* Step3-1 設定查詢式 */ var query = Builders <MembersCollection> .Filter.Eq(e => e.uid, request.uid); /* Step3-2 進行查詢的操作,並取得會員資訊 */ var doc = membersCollection.Find(query).ToListAsync().Result.FirstOrDefault(); if (doc != null) { /* Step3-3-1 當資料庫中存在該會員時,進行修改會員資訊的操作 */ var update = Builders <MembersCollection> .Update .Set("name", request.name) .Set("phone", request.phone); membersCollection.UpdateOne(query, update); } else { /* Step3-3-2 當資料庫中沒有該會員時,設定Response的ok欄位與errMsg欄位 */ response.ok = false; response.errMsg = "編號為" + request.uid + "的會員不存在,請確認會員編號。"; } return(response); }
public EditMemberResponse Put(EditMemberRequest request) { var response = new EditMemberResponse(); MongoClient client = new MongoClient("mongodb://localhost:27017"); MongoDatabaseBase db = client.GetDatabase("ntut") as MongoDatabaseBase; var memberCollection = db.GetCollection <MembersCollection>("members"); var listOfWriteModels = new List <WriteModel <MembersCollection> >(); var uids = request.members.Select(e => e.uid).ToList(); var existQuery = Builders <MembersCollection> .Filter.In(e => e.Uid, uids); var doc = memberCollection.Find(existQuery).ToList(); if (doc.Count > 0) { var existUIDList = doc.Select(e => e.Uid).ToList(); //移除不存在在資料庫的會員ID var notExistList = request.members.Where(e => !existUIDList.Contains(e.uid)).Select(e => e.uid).ToList(); var existUid = string.Join(",", notExistList); response.ok = false; response.errMsg = "編號為" + existUid + "的會員不存在在資料庫,請重新確認這些會員編號。"; request.members.RemoveAll(e => !existUIDList.Contains(e.uid)); } foreach (var member in request.members) { var query = Builders <MembersCollection> .Filter.Eq(e => e.Uid, member.uid); var update = Builders <MembersCollection> .Update .Set(e => e.Name, member.name) .Set(e => e.Phone, member.phone); var updateOneModel = new UpdateOneModel <MembersCollection>(query, update); listOfWriteModels.Add(updateOneModel); } memberCollection.BulkWriteAsync(listOfWriteModels); return(response); }
/// <summary> /// 新增會員 /// </summary> /// <param name="request"></param> /// <returns></returns> public AddMemberResponse Post(AddMemberRequest request) { //輸出結果 var response = new AddMemberResponse(); // 連接MongoDB伺服器 MongoClient client = new MongoClient("mongodb://localhost:27017"); //取得資料庫(Database)和集合(collection) MongoDatabaseBase db = (MongoDatabaseBase)client.GetDatabase("ntut"); //取得members集合(collection) var membersCollection = db.GetCollection <MembersCollection>("members"); //查詢是否已存在資料 var query = Builders <MembersCollection> .Filter.Eq(e => e.uid, request.uid); var doc = membersCollection.Find(query).ToListAsync().Result.FirstOrDefault(); if (doc == null) { //新增資料 membersCollection.InsertOne( new MembersCollection() { _id = ObjectId.GenerateNewId(), uid = request.uid, name = request.name, phone = request.phone }); } else { response.ok = false; response.errMsg = "編號:" + request.uid + "的會員已存在。"; } return(response); }
protected override void Execute(CodeActivityContext context) { var database_name = DB_Name.Get(context); var coll_name = Collection_Name.Get(context); var database_ip = DB_Server_IP.Get(context); string Query_Field = Filter_Field.Get(context); dynamic Query_Value = Filter_Value.Get(context); string Update_Key = Update_Field.Get(context); dynamic Update_Val = Update_Value.Get(context); Console.WriteLine(typeoffilter); List <string> output = new List <string>(); MongoClient mongoclient = new MongoClient(database_ip); var db_list = mongoclient.ListDatabaseNames().ToList(); if (db_list.Contains(database_name)) { //Connects to the Exsisting Database or Creates new Database MongoDatabaseBase myDB = (MongoDatabaseBase)mongoclient.GetDatabase(database_name); //Creates new collection //var colll=myDB.CreateCollection(coll_name); var coll_list = myDB.ListCollectionNames().ToList(); if (coll_list.Contains(coll_name)) { var collection = myDB.GetCollection <BsonDocument>(coll_name); if (typeoffilter.ToString() == "EQ") { var query_e = Builders <BsonDocument> .Filter.Eq(Query_Field, Query_Value); var update_1 = Builders <BsonDocument> .Update.Set(Update_Key, Update_Val); // update modifiers collection.UpdateMany(query_e, update_1); } else if (typeoffilter.ToString() == "GT") { var query_e = Builders <BsonDocument> .Filter.Gt(Query_Field, Query_Value); var update_1 = Builders <BsonDocument> .Update.Set(Update_Key, Update_Val); // update modifiers collection.UpdateMany(query_e, update_1); } else if (typeoffilter.ToString() == "GTE") { var query_e = Builders <BsonDocument> .Filter.Gte(Query_Field, Query_Value); var update_1 = Builders <BsonDocument> .Update.Set(Update_Key, Update_Val); // update modifiers collection.UpdateMany(query_e, update_1); } else if (typeoffilter.ToString() == "LT") { var query_e = Builders <BsonDocument> .Filter.Lt(Query_Field, Query_Value); var update_1 = Builders <BsonDocument> .Update.Set(Update_Key, Update_Val); // update modifiers collection.UpdateMany(query_e, update_1); } else if (typeoffilter.ToString() == "LTE") { var query_e = Builders <BsonDocument> .Filter.Lte(Query_Field, Query_Value); var update_1 = Builders <BsonDocument> .Update.Set(Update_Key, Update_Val); // update modifiers collection.UpdateMany(query_e, update_1); } } else { Console.Write("Cannot find Collection"); } } else { Console.Write("Cannot find DB"); } }