Advertisement
NgThanhPhuc

MongoDB_FindOneAndUpdateOptions

Feb 13th, 2016
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.01 KB | None | 0 0
  1. using MongoDB.Bson;
  2. using MongoDB.Bson.IO;
  3. using MongoDB.Bson.Serialization;
  4. using MongoDB.Bson.Serialization.Attributes;
  5. using MongoDB.Driver;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace M101DotNet
  12. {
  13.     class Program
  14.     {
  15.         static void Main(string[] args)
  16.         {
  17.             MainAsync(args).GetAwaiter().GetResult();
  18.             Console.WriteLine("Press enter");
  19.             Console.ReadLine();
  20.  
  21.         }
  22.  
  23.         static async Task MainAsync(string[] args)
  24.         {
  25.             var client = new MongoClient();
  26.             var db = client.GetDatabase("Phucdb");
  27.             var col = db.GetCollection<Widget>("widgets");
  28.             // Drop r Insert
  29.             await db.DropCollectionAsync("widgets");
  30.             var docs = Enumerable.Range(0, 10).Select(i => new Widget { Id = i, X = i });
  31.             await col.InsertManyAsync(docs);
  32.             //FindOneAndUpdate
  33.             var result = await col.FindOneAndUpdateAsync<Widget>(
  34.                 x => x.X > 5,
  35.                 Builders<Widget>.Update.Inc(x => x.X, 555),
  36.                 new FindOneAndUpdateOptions<Widget, Widget>
  37.                 {
  38.                     ReturnDocument = ReturnDocument.After, // Hiện gtri trc' or sau chỉnh sữa
  39.                     Sort =  Builders<Widget>.Sort.Descending(x=>x.X) // Sort gtri chỉnh sữa theo ý muốn
  40.                 }
  41.             );
  42.             // Xuat dòng vừa dc thực thi
  43.             Console.WriteLine(result);
  44.             Console.WriteLine();
  45.             // Xuat
  46.             await col.Find(new BsonDocument()).ForEachAsync(x => Console.WriteLine(x));
  47.         }
  48.         private class Widget
  49.         {
  50.             public int Id { get; set; }
  51.             [BsonElement("x")]
  52.             public int X { get; set; }
  53.            
  54.             public override string ToString()
  55.             {
  56.                 return string.Format("Id: {0}, X: \"{1}\"", Id, X);
  57.             }
  58.         }
  59.     }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement