无法通过 2sphere 找到元素

我来是因为我需要实现地理计算,但是,它不起作用。我目前正在使用这个包globalsign/mgo


从文档中我们有这个:


db.<collection>.find( { <location field> :

        { $near :

            { $geometry :

                { type : "Point" ,

                     coordinates : [ <longitude> , <latitude> ] } ,

                     $maxDistance : <distance in meters>,

                } 

            }

       }

  

查询2dsphere索引:https://docs.mongodb.com/manual/tutorial/query-a-2dsphere-index/ 2dsphere索引:https://docs.mongodb.com/manual/core/2dsphere/


所以我有以下内容:

import (

    "github.com/globalsign/mgo/bson"

    "shared/models"

    "time"

)


type Address struct {

    ID                 *bson.ObjectId `protobuf:"bytes,1,opt,name=id,proto3" json:"_id,omitempty" bson:"_id"`

    IsArchived         bool           `protobuf:"varint,2,opt,name=IsArchived,proto3" json:"is_archived,omitempty" bson:"is_archived"`

    CreatedAt          time.Time      `protobuf:"varint,3,opt,name=CreatedAt,proto3" json:"created_at,omitempty" bson:"created_at"`

    UpdatedAt          time.Time      `protobuf:"varint,4,opt,name=UpdatedAt,proto3" json:"update_at,omitempty" bson:"updated_at"`

    PlaceID            *bson.ObjectId `protobuf:"bytes,5,opt,name=PlaceID,proto3" json:"place_id,omitempty" bson:"place_id"`

    CountryCode        string         `protobuf:"bytes,6,opt,name=CountryCode,proto3" json:"country_code,omitempty" bson:"country_code,omitempty"`

    AdministrativeArea string         `protobuf:"bytes,7,opt,name=AdministrativeArea,proto3" json:"administrative_area,omitempty" bson:"administrative_area,omitempty"`

由此,我收到以下错误:


“错误处理查询:ns=DBNAME.addressDocumentTree:GEONEAR field=location maxdist=5e+06 isNearSphere=0\nSort:{}\nProj:{}\n 规划器返回错误:无法找到 $geoNear 查询的索引”


我在程序初始化时确保我的索引


森林海
浏览 93回答 1
1回答

慕村9548890

终于找到了问题..实际上,我没有以正确的方式创建索引..// EnsureIndex force ids to be uniquefunc EnsureAddressIndex(session *mgo.Session) error {&nbsp; &nbsp; _session := session.Copy()&nbsp; &nbsp; defer _session.Close()&nbsp; &nbsp; c := _session.DB(constants.DBName).C(addressDocument)&nbsp; &nbsp; // Might be needed one day&nbsp; &nbsp; pIndex := mgo.Index{&nbsp; &nbsp; &nbsp; &nbsp; Key:&nbsp; []string{"$2dsphere:location"},&nbsp; &nbsp; &nbsp; &nbsp; Bits: 26,&nbsp; &nbsp; }&nbsp; &nbsp; err := c.EnsureIndex(pIndex)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; return nil}在索引声明中,我有以下行:pIndex := mgo.Index{&nbsp; &nbsp; Key:&nbsp; []string{"location:2dsphere"},&nbsp; &nbsp; Bits: 26,}但正确的写法是pIndex := mgo.Index{&nbsp; &nbsp; Key:&nbsp; []string{"$2dsphere:location"},&nbsp; &nbsp; Bits: 26,}希望能帮助到你 !
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go