hafei / hafei.github.io

Home Page
https://hafei.github.io
0 stars 0 forks source link

translate mongodb shell script to C# #21

Open hafei opened 5 years ago

hafei commented 5 years ago
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Threading.Tasks;

namespace MongoDBQueryCode
{
    class Program
    {
        static async Task _Main()
        {
            //MongoDefaults.GuidRepresentation = MongoDB.Bson.GuidRepresentation.Standard;
            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("BookstoreDb");
            var collection = database.GetCollection<BsonDocument>("Books");

            //Created with NoSQLBooster, the essential IDE for MongoDB - https://nosqlbooster.com
            var filter = new BsonDocument(){    
                {"Author", new BsonDocument(){        
                    {"$in", new BsonArray(){new BsonRegularExpression("^Meng "),new BsonRegularExpression("^Meng")}}
                }}
            };            

            using (var cursor = await collection.FindAsync(filter))
            {
                while (await cursor.MoveNextAsync())
                {
                    var batch = cursor.Current;
                    foreach (var document in batch)
                    {
                        Console.WriteLine(document.GetElement("_id"));
                    }
                }
            }

        }

        static void Main(string[] args)
        {
            _Main().Wait();
        }
    }
}