【问题标题】:How to display the results of MongoDB $near query如何显示 MongoDB $near 查询的结果
【发布时间】:2018-03-07 06:27:12
【问题描述】:

所以我在这里运行旧版 $near 搜索

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

但我对我所发现的实际情况感到困惑。据我了解和研究,搜索将显示按最接近给定坐标的位置排序的文档,但我为尝试查看文档所做的任何事情都只会输出这个大查询。我不知道这个巨大的 Query 是什么意思,我对 mongo 和 javascript 并不熟悉,我想弄清楚我是如何看到 $near 做了什么的。

Query {
_mongooseOptions: {},
mongooseCollection: 
 NativeCollection {
 collection: Collection { s: [Object] },
 opts: 
  { bufferCommands: true,
    capped: false,
    '$wasForceClosed': undefined },
 name: 'soundspots',
 collectionName: 'soundspots',
 conn: 
  NativeConnection {
    base: [Object],
    collections: [Object],
    models: [Object],
    config: [Object],
    replica: false,
    hosts: null,
    host: 'localhost',
    port: 27017,
    user: null,
    pass: null,
    name: 'user_account',
    options: null,
    otherDbs: [],
    states: [Object],
    _readyState: 1,
    _closeCalled: false,
    _hasOpened: true,
    _listening: false,
    _connectionOptions: [Object],
    '$initialConnection': [Object],
    db: [Object],
    client: [Object] },
 queue: [],
 buffer: false,
 emitter: 
  EventEmitter {
    domain: null,
    _events: {},
    _eventsCount: 0,
    _maxListeners: undefined } },
model: 
{ [Function: model]
 hooks: Kareem { _pres: [Object], _posts: [Object] },
 base: 
  Mongoose {
    connections: [Object],
    models: [Object],
    modelSchemas: [Object],
    options: [Object],
    _pluralize: [Function: pluralize],
    plugins: [Object] },
 modelName: 'soundspot',
 model: [Function: model],
 db: 
  NativeConnection {
    base: [Object],
    collections: [Object],
    models: [Object],
    config: [Object],
    replica: false,
    hosts: null,
    host: 'localhost',
    port: 27017,
    user: null,
    pass: null,
    name: 'user_account',
    options: null,
    otherDbs: [],
    states: [Object],
    _readyState: 1,
    _closeCalled: false,
    _hasOpened: true,
    _listening: false,
    _connectionOptions: [Object],
    '$initialConnection': [Object],
    db: [Object],
    client: [Object] },
 discriminators: undefined,
 '$appliedMethods': true,
 authenticate: [Function],
 serializeUser: [Function],
 deserializeUser: [Function],
 register: [Function],
 findByUsername: [Function],
 createStrategy: [Function],
 '$appliedHooks': true,
 schema: 
  Schema {
    obj: [Object],
    paths: [Object],
    aliases: {},
    subpaths: {},
    virtuals: [Object],
    singleNestedPaths: {},
    nested: [Object],
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: [Object],
    statics: [Object],
    tree: [Object],
    query: {},
    childSchemas: [],
    plugins: [Object],
    s: [Object],
    _userProvidedOptions: undefined,
    options: [Object],
    '$globalPluginsApplied': true },
 collection: 
  NativeCollection {
    collection: [Object],
    opts: [Object],
    name: 'soundspots',
    collectionName: 'soundspots',
    conn: [Object],
    queue: [],
    buffer: false,
    emitter: [Object] },
 Query: { [Function] base: [Object] },
 '$__insertMany': [Function],
 '$init': Promise { [Object], catch: [Function] } },
schema: 
Schema {
 obj: 
  { name: [Function: String],
    key: [Function: String],
    connected: [Object],
    type: [Object],
    location: [Object],
    playlist: [Object] },
 paths: 
  { name: [Object],
    key: [Object],
    'connected.username': [Object],
    type: [Object],
    'location.type': [Object],
    'location.coordinates': [Object],
    'location.longitude': [Object],
    'location.latitude': [Object],
    'playlist.title': [Object],
    'playlist.file': [Object],
    'playlist.votes': [Object],
    _id: [Object],
    username: [Object],
    hash: [Object],
    salt: [Object],
    __v: [Object] },
 aliases: {},
 subpaths: {},
 virtuals: { id: [Object] },
 singleNestedPaths: {},
 nested: { connected: true, location: true, playlist: true },
 inherits: {},
 callQueue: [],
 _indexes: [],
 methods: 
  { setPassword: [Function],
    changePassword: [Function],
    authenticate: [Function] },
 statics: 
  { authenticate: [Function],
    serializeUser: [Function],
    deserializeUser: [Function],
    register: [Function],
    findByUsername: [Function],
    createStrategy: [Function] },
 tree: 
  { name: [Function: String],
    key: [Function: String],
    connected: [Object],
    type: [Object],
    location: [Object],
    playlist: [Object],
    _id: [Object],
    username: [Object],
    hash: [Object],
    salt: [Object],
    __v: [Function: Number],
    id: [Object] },
 query: {},
 childSchemas: [],
 plugins: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
 s: { hooks: [Object] },
 _userProvidedOptions: undefined,
 options: 
  { typeKey: 'type',
    id: true,
    noVirtualId: false,
    _id: true,
    noId: false,
    validateBeforeSave: true,
    read: null,
    shardKey: null,
    autoIndex: null,
    minimize: true,
    discriminatorKey: '__t',
    versionKey: '__v',
    capped: false,
    bufferCommands: true,
    strict: true,
    pluralization: true },
 '$globalPluginsApplied': true },
op: 'find',
options: {},
_conditions: 
{ location: { '$near': [Object], '$maxDistance': 100 },
 _mongooseOption: 'find' },
_fields: undefined,
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection: 
NodeCollection {
 collection: 
  NativeCollection {
    collection: [Object],
    opts: [Object],
    name: 'soundspots',
    collectionName: 'soundspots',
    conn: [Object],
    queue: [],
    buffer: false,
    emitter: [Object] },
 collectionName: 'soundspots' },
_traceFunction: undefined }
Query {
 _mongooseOptions: {},
 mongooseCollection: 
 NativeCollection {
 collection: Collection { s: [Object] },
 opts: 
  { bufferCommands: true,
    capped: false,
    '$wasForceClosed': undefined },
 name: 'soundspots',
 collectionName: 'soundspots',
 conn: 
  NativeConnection {
    base: [Object],
    collections: [Object],
    models: [Object],
    config: [Object],
    replica: false,
    hosts: null,
    host: 'localhost',
    port: 27017,
    user: null,
    pass: null,
    name: 'user_account',
    options: null,
    otherDbs: [],
    states: [Object],
    _readyState: 1,
    _closeCalled: false,
    _hasOpened: true,
    _listening: false,
    _connectionOptions: [Object],
    '$initialConnection': [Object],
    db: [Object],
    client: [Object] },
 queue: [],
 buffer: false,
 emitter: 
  EventEmitter {
    domain: null,
    _events: {},
    _eventsCount: 0,
    _maxListeners: undefined } },
 model: 
   { [Function: model]
 hooks: Kareem { _pres: [Object], _posts: [Object] },
 base: 
  Mongoose {
    connections: [Object],
    models: [Object],
    modelSchemas: [Object],
    options: [Object],
    _pluralize: [Function: pluralize],
    plugins: [Object] },
 modelName: 'soundspot',
 model: [Function: model],
 db: 
  NativeConnection {
    base: [Object],
    collections: [Object],
    models: [Object],
    config: [Object],
    replica: false,
    hosts: null,
    host: 'localhost',
    port: 27017,
    user: null,
    pass: null,
    name: 'user_account',
    options: null,
    otherDbs: [],
    states: [Object],
    _readyState: 1,
    _closeCalled: false,
    _hasOpened: true,
    _listening: false,
    _connectionOptions: [Object],
    '$initialConnection': [Object],
    db: [Object],
    client: [Object] },
 discriminators: undefined,
 '$appliedMethods': true,
 authenticate: [Function],
 serializeUser: [Function],
 deserializeUser: [Function],
 register: [Function],
 findByUsername: [Function],
 createStrategy: [Function],
 '$appliedHooks': true,
 schema: 
  Schema {
    obj: [Object],
    paths: [Object],
    aliases: {},
    subpaths: {},
    virtuals: [Object],
    singleNestedPaths: {},
    nested: [Object],
    inherits: {},
    callQueue: [],
    _indexes: [],
    methods: [Object],
    statics: [Object],
    tree: [Object],
    query: {},
    childSchemas: [],
    plugins: [Object],
    s: [Object],
    _userProvidedOptions: undefined,
    options: [Object],
    '$globalPluginsApplied': true },
 collection: 
  NativeCollection {
    collection: [Object],
    opts: [Object],
    name: 'soundspots',
    collectionName: 'soundspots',
    conn: [Object],
    queue: [],
    buffer: false,
    emitter: [Object] },
 Query: { [Function] base: [Object] },
 '$__insertMany': [Function],
 '$init': Promise { [Object], catch: [Function] } },
 schema: 
  Schema {
  obj: 
  { name: [Function: String],
    key: [Function: String],
    connected: [Object],
    type: [Object],
    location: [Object],
    playlist: [Object] },
   paths: 
   { name: [Object],
    key: [Object],
    'connected.username': [Object],
    type: [Object],
    'location.type': [Object],
    'location.coordinates': [Object],
    'location.longitude': [Object],
    'location.latitude': [Object],
    'playlist.title': [Object],
    'playlist.file': [Object],
    'playlist.votes': [Object],
    _id: [Object],
    username: [Object],
    hash: [Object],
    salt: [Object],
    __v: [Object] },
 aliases: {},
 subpaths: {},
 virtuals: { id: [Object] },
 singleNestedPaths: {},
 nested: { connected: true, location: true, playlist: true },
 inherits: {},
 callQueue: [],
 _indexes: [],
 methods: 
  { setPassword: [Function],
    changePassword: [Function],
    authenticate: [Function] },
 statics: 
  { authenticate: [Function],
    serializeUser: [Function],
    deserializeUser: [Function],
    register: [Function],
    findByUsername: [Function],
    createStrategy: [Function] },
 tree: 
  { name: [Function: String],
    key: [Function: String],
    connected: [Object],
    type: [Object],
    location: [Object],
    playlist: [Object],
    _id: [Object],
    username: [Object],
    hash: [Object],
    salt: [Object],
    __v: [Function: Number],
    id: [Object] },
 query: {},
 childSchemas: [],
 plugins: [ [Object], [Object], [Object], [Object], [Object], [Object] ],
 s: { hooks: [Object] },
 _userProvidedOptions: undefined,
 options: 
  { typeKey: 'type',
    id: true,
    noVirtualId: false,
    _id: true,
    noId: false,
    validateBeforeSave: true,
    read: null,
    shardKey: null,
    autoIndex: null,
    minimize: true,
    discriminatorKey: '__t',
    versionKey: '__v',
    capped: false,
    bufferCommands: true,
    strict: true,
    pluralization: true },
 '$globalPluginsApplied': true },
 op: 'find',
 options: {},
 _conditions: 
 { location: { '$near': [Object], '$maxDistance': 100 },
 _mongooseOption: 'find' },
 _fields: undefined,
 _update: undefined,
 _path: undefined,
 _distinct: undefined,
 _collection: 
 NodeCollection {
 collection: 
  NativeCollection {
    collection: [Object],
    opts: [Object],
    name: 'soundspots',
    collectionName: 'soundspots',
    conn: [Object],
    queue: [],
    buffer: false,
    emitter: [Object] },
 collectionName: 'soundspots' },
 _traceFunction: undefined }

【问题讨论】:

    标签: javascript mongodb mongodb-query location


    【解决方案1】:

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

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

    如果没有索引(2dsphere),您将无法在您的aggregatation 中使用$geoNear$near。 例如:

    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 允许您在以米为单位的指定距离范围内查找位置。 num 就像 $limit 你可以限制返回多少数据。

    【讨论】:

    • 非常感谢!但是我在哪里/如何准确显示结果?我需要做什么才能使用并查看结果?
    • 首先你需要数据来比较它。 { "_id" : ObjectId("5a698d995c4a4fc350915676"), "name" : "Huey's Knight Club", "address" : "164 Easton Ave, New Brunswick, NJ 08901, USA", "radius" : 251, "updatedAt" : ISODate("2018-02-08T11:43:46.524Z"), "location" : [ -74.4542719, 40.4997539 ], "duration" : null, "infinite" : false, "isActive" : false, "lastActive" : null } 之后,您只能使用 $geoNearaggregation。首先,您需要在Robo 3T 中执行查询以查看结果。
    • 所以我有一个正在比较的填充集合,所以我对某些事情有点模糊。所以我所要做的就是运行聚合?聚合对“排序”对象有什么作用,数据放在哪里?我必须将它保存到变量中,还是它只是自动为我查询它,如果是的话,在哪里?查询数据的整个概念给我带来了麻烦。
    • 数据已经存入数据库,您只需对它们执行aggregation。您需要查看此链接 => docs.mongodb.com/manual/reference/operator/aggregation/geoNear
    • 我阅读了文档,我想我理解它应该如何工作,我认为我的索引很好,但我收到了这个错误 MongoError: geoNear command failed: { ok: 0.0, errmsg: "geoNear 没有地理索引" }
    【解决方案2】:

    这是因为您打印的是 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 的示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-16
      • 2019-11-09
      • 2020-07-03
      • 1970-01-01
      • 1970-01-01
      • 2014-03-06
      • 1970-01-01
      相关资源
      最近更新 更多