How to make comlex query MongoDB with Powershell

≡放荡痞女 提交于 2019-12-03 21:02:51

please find solution below: It is a flexible code using c# inside powershell script and latest mongo drivers (2.2.3) - so you can play with c# code as required :-)

$mongoDbDriverPath = "C:\work\mongo"
$dbName = "deser"
$collectionName = "Foo"
$Assem = ( "$($mongoDbDriverPath)\MongoDB.Bson.dll", "$($mongoDbDriverPath)\MongoDB.Driver.dll","$($mongoDbDriverPath)\MongoDB.Driver.Core.dll") 

$Source = @” 
namespace profesor79
{
    using System.Collections.Generic;

    using MongoDB.Bson;
    using MongoDB.Bson.Serialization.Attributes;
    using MongoDB.Driver;

    public static class Executor
    {
        public static List<Foo> GetData()
        {
            var connectionString = "mongodb://localhost:27017";
            var _client = new MongoClient(connectionString);
            var _database = _client.GetDatabase("deser");
            var cole = _database.GetCollection<Foo>("Foo");
            cole.InsertOne(new Foo());

            var data = cole.Find<Foo>((new BsonDocument())).ToList();
            return data;
        }

        public class Foo
        {
            public ObjectId Id { get; set; }
            [BsonDictionaryOptions]
            public Dictionary<string, string> Bar = new Dictionary<string, string>() { { "1", "text" }, { "2", "text" } };

        }
    }
}


"@

Add-Type  -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp  

[profesor79.Executor]::GetData()

see screenshot:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!