Mongo。 C#。我如何执行字符串作为 mongo 查询

Mongo. C#. How can i execute string as mongo query

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

我就是想要这样

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

不,在这种情况下,您可以做的最好的事情是使用接近 shell db.runCommand({ ping : 1 })

db.RunCommand<BsonDocument>("{ ping : 1 }") (c#)

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

            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 流。