如何显示MongoDB $ near查询的结果

时间:2018-03-07 06:27:12

标签: javascript mongodb mongodb-query location

所以我在这里运行遗产$ near搜索

Dockerfile

但我对我发现的实际情况感到困惑。根据我的理解和研究,搜索将显示按最接近给定坐标的位置排序的文档,但我尝试查看文档的任何内容仅输出此大查询。我不知道这个巨大的查询意味着什么,我不熟悉mongo和javascript,我想弄清楚我是怎么看到$ near附近做了什么。

SoundSpot.find(
{ location : { $near : [ longitude, latitude ], $maxDistance: 100 } }
);

2 个答案:

答案 0 :(得分:0)

每当您需要应用$geometry个查询时,请不要忘记在您的架构中应用索引,如下所示:

  location: {
  type: [Number], // <Longitude, Latitude>
  index: {
      type: '2dsphere',
      sparse: false
  },
  required: true,
},

没有索引(2dsphere),您无法在$geoNear中使用$nearaggregatation。 例如:

db.places.aggregate([
{
  $geoNear: {
     near: { type: "Point", coordinates: [ -73.99279 , 40.719296 ] }, 
    //coordinates: [longitude, latitude]
     distanceField: "dist.calculated",
     maxDistance: 200, //Meters
     includeLocs: "dist.location",
     num: 5,
     spherical: true
  }
 }
]);

在上面的代码附近找到你要求的坐标最近的地方。 distanceField找到以米为单位的距离并显示如下:

    "dist" : {
    "calculated" : 42107.6268114667, //Meters
    "location" : [ 
        -74.167457, 
        40.3650877
    ]
}

maxDistance可让您在meteres中找到指定距离范围内的位置。 num$limit类似,您可以限制返回的数据量。

答案 1 :(得分:0)

这是因为您正在打印Query对象的值,而不是迭代结果。

您正在使用Mongoose,但如果您使用本机节点驱动程序,则问题是相同的。

例如,如果我的test集合中有一个文档:

> db.test.find()
{ "_id": 0, "a": 1, "b": 1, "c": 1, "d": 1 }

现在,如果我运行以下代码,它将具有与您所看到的类似的输出:

MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
    db.db('test').collection('test').find({}, function(err, res) {
        console.log(res);
    });
});

请注意,在上面的代码中,我打印了res对象。代码的输出是:

Cursor {
  pool: null,
  server: null,
  disconnectHandler:
   Store {
     s: { storedOps: [], storeOptions: [Object], topology: [Server] },
     length: [Getter] },
  bson: BSON {},
  ns: 'test.test',
  cmd:
   { find: 'test.test',
     limit: 0,
     skip: 0,
     query: {},
     readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
     slaveOk: true },
  options:
   { readPreference: ReadPreference { mode: 'primary', tags: undefined, options: undefined },
     skip: 0,
     limit: 0,
     raw: undefined,
     hint: null,
     timeout: undefined,
     slaveOk: true,
     db:
.... many more lines ....

不同之处在于,我看到Query对象,而不是Cursor对象。

现在,如果我迭代res

MongoClient.connect('mongodb://localhost:27017/test', (err, db) => {
    db.db('test').collection('test').find({}, function(err, res) {
        res.forEach(doc => {console.log(doc)});
    });
});

它会打印实际文件:

{ _id: 0, a: 1, b: 1, c: 1, d: 1 }

Query object上查看Mongoose的页面,了解Mongoose中的示例。

相关问题