qiniu / qmgo

Qmgo - The Go driver for MongoDB. It‘s based on official mongo-go-driver but easier to use like Mgo.
Apache License 2.0
1.31k stars 155 forks source link

How To Create a 2dsphere index on geojson object field #305

Open ghost opened 1 year ago

ghost commented 1 year ago

I am trying these 2 ways to create a 2dsphere index on a collection, but both failed. Both created a regular index. The first creates a compound index and the second creates a regular index.

import (
    "context"

    "github.com/paulmach/orb/geojson"
    "github.com/qiniu/qmgo/options"
    "go.mongodb.org/mongo-driver/bson"
    "go.mongodb.org/mongo-driver/mongo"
)

// StoreGeoJSONCollection is the collection name for the store geojson model
const StoreGeoJSONCollection = "stores_geojson"

// StoreGeoJSON represents the store geojson model
type StoreGeoJSON struct {
    Model `bson:",inline"`

    StoreId           ObjectID                   `bson:"store_id"            json:"store_id"            validate:"required"`
    StoreName         string                     `bson:"store_name"          json:"store_name"          validate:"required"`
    Title             string                     `bson:"title"               json:"title"               validate:"required"`
    Geojson           *geojson.FeatureCollection `bson:"geojson"             json:"geojson"             validate:"required"`
    DeliveryFee       float64                    `bson:"delivery_fee"        json:"delivery_fee"`
    MinimumOrderValue float64                    `bson:"minimum_order_value" json:"minimum_order_value"`
    DeliveryProductId *string                    `bson:"delivery_product_id" json:"delivery_product_id"`
}

// CollectionName returns the collection name for the store geojson model
func (StoreGeoJSON) CollectionName() string {
    return StoreGeoJSONCollection
}

// Indexes returns the indexes for the store geojson model
func (StoreGeoJSON) Indexes() []options.IndexModel {
    return []options.IndexModel{
        {
            Key:          []string{"geojson.features.geometry", "2dsphere"},
            IndexOptions: Index().SetSphereVersion(3),
        },
        {
            Key:          []string{"geojson.features.geometry"},
            IndexOptions: Index().SetSphereVersion(3),
        },
    }
}

Indexes Screenshot

image

Please share the correct way to create 2dsphere indexes using qmgo.

jiangz222 commented 9 months ago

Hi, please share your complete codes to create index!