【问题标题】:Mongo. C#. How can i execute string as mongo query蒙哥。 C#。我如何执行字符串作为 mongo 查询
【发布时间】:2021-09-15 10:04:15
【问题描述】:

假设我有一个字符串。 " db.getCollection("somecollection").find({})"。我可以在 C# 中将此字符串作为查询执行吗?即我得到一个字符串。我只是将它作为查询执行,但在 c# 中

我只想这样

string query = "db.getCollection("somename")";
Mongo.execute(query);

【问题讨论】:

  • 定义你的完整场景你为此做了什么。技术上这是不支持的,但为此你可以在 c# 中运行直接 mongo 命令来获得结果
  • 我刚刚更新了帖子。请检查

标签: c# mongodb mongo-shell


【解决方案1】:

不,在这种情况下你能做的最好的事情是使用db.RunCommand<BsonDocument>("{ ping : 1 }") (c#),它接近于 shell db.runCommand({ ping : 1 })

更新: 你也可以看看这个How to execute mongo commands through shell scripts?,我对此并不熟悉,在大多数情况下,它在 Windows 和 5.0 服务器上对我不起作用,除了简单的一个:mongo --eval "printjson(db.serverStatus())",但如果你将能够使这个建议的脚本mongo < script.js(或类似的)在例如 shell 中工作,您将能够将您的随机查询放入这个文件(script.js)然后,将此文件作为参数添加到创建过程类似于:

            using (var process = new Process())
            {
                // arguments below may require the whole path to the files
                process.StartInfo.Arguments = "script.js";
                process.StartInfo.FileName = "mongo"; 

                process.Start();
            }

要读取结果,您需要分析process.StandardOutput/process.StandardError 流。

【讨论】:

  • 但是一定有办法做到的。
  • Mongo 除了 runCommand 没有提供任何其他方式,你可以通过反射或 codedom 实现这个目标:docs.microsoft.com/en-us/dotnet/framework/…,但这需要额外的步骤
  • 但是,如果我正确理解您的需求,runCommand docs.mongodb.com/manual/reference/command 很可能就是您所需要的
  • runCommand 要求 JSON 格式为字符串。
  • 它需要 BSON 格式的 MQL 命令。它可以是 BsonDocument 或字符串。
猜你喜欢
  • 2017-03-29
  • 2013-04-27
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多