使用 c# 驱动程序 v2 执行原始 Mongodb 查询

Afl*_*red 7 c# mongodb mongodb-.net-driver

我有以下代码:

MongoClient m = new MongoClient();
        var db = m.GetDatabase("PopupRentals");



        string cmdDoc = (@"
                            db.Rentals.find({polygons:
                                             {$geoIntersects:
                                                 {$geometry:{ 'type' : 'Point',
                                                      'coordinates' : [ 17.3734, 78.4738 ]
                                }
                            }
                                              }
                                         });");

        var cmd = new JsonCommand<BsonDocument>(cmdDoc);

        var res = db.RunCommand(cmd);

        var result = db.GetCollection<RentalProperty>("Rentals");
Run Code Online (Sandbox Code Playgroud)

我正在使用标准的 mongodb v2 驱动程序。

一旦我执行查询,我会在关于

db.RunCommand(cmd);

System.FormatException: 'JSON reader was expecting a value but found 'db'.'
Run Code Online (Sandbox Code Playgroud)

我没有丝毫线索为什么这不起作用。它在 Robo 中效果很好。

Jos*_*hee 5

您的string cmdDoc格式不正确,无法按照您想要的方式使用它。根据命令MongoDB 文档find,您的字符串应如下所示:

string cmdDoc = @"
                    {
                      find: "Rentals",
                      filter: {
                                polygons: {
                                            $geoIntersects: {
                                                              $geometry: { 
                                                                           'type' : 'Point',
                                                                           'coordinates' : [ 17.3734, 78.4738 ]
                                                                         }
                                                            }
                                          }
                              }
                    }"
Run Code Online (Sandbox Code Playgroud)

或者没有用于格式化的所有额外空格:

string cmdDoc = @"{
                    find: "Rentals",
                    filter: { polygons: { $geoIntersects: { $geometry: { 'type' : 'Point', 'coordinates' : [ 17.3734, 78.4738 ] } } } }
                  }"
Run Code Online (Sandbox Code Playgroud)