【问题标题】:Query Mongo Collection from Powershell script从 Powershell 脚本查询 Mongo 集合
【发布时间】:2019-12-14 17:55:06
【问题描述】:

我需要运行一个从管道查询 MongoDB 集合的 powershell 脚本。我正在使用最新的 MongoDB 驱动程序 2.9.3。我写的脚本如下 -

$Assem = ("D:\PoweshellMongoDB\Drivers\MongoDB.Bson.dll", "D:\PoweshellMongoDB\Drivers\MongoDB.Driver.dll", "D:\PoweshellMongoDB\Drivers\MongoDB.Driver.Core.dll")

$Source = @"
using MongoDB.Bson;
using MongoDB.Driver;
using System;

namespace MongoDBSample
{
    public static class MongoRepository
    {
        public static void Connect()
        {
            try
            {
                var mongoClient = new MongoClient("mongodb://localhost:27017");
                var database = mongoClient.GetDatabase("ILP4");
                var collection = database.GetCollection<BsonDocument>("Issues");

                var count = collection.CountDocumentsAsync(new BsonDocument()).ConfigureAwait(false);

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
"@

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

[MongoDBSample.MongoRepository]::Connect()

但是当我调试脚本时,我遇到了错误 -

Exception calling "Connect" with "0" argument(s): "Could not load file or assembly 'MongoDB.Driver, Version=2.9.3.0, Culture=neutral, PublicKeyToken=null' or 
one of its dependencies. The system cannot find the file specified."
At D:\PoweshellMongoDB\PowerMongo.ps1:34 char:1
+ [MongoDBSample.MongoRepository]::Connect()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : FileNotFoundException

我不确定我缺少哪个参考。有更好的方法吗?还是我需要将驱动程序更新到旧版本?请指教。

【问题讨论】:

标签: mongodb powershell .net-core mongodb-.net-driver


【解决方案1】:

我找到了解决方案。我创建了一个使用 MongoDB 驱动程序 2.3.1 连接到 MongoDB 的 .NET Framework 类库。在我的管道中,我创建了设置 - 从源代码管理中签出库代码,构建和发布 dll,从我的内联 powershell 脚本中,我引用了这个 dll 并执行它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多