Beispiel #1
0
// Get reteives a record given the id
func Get(collectionName, id string) (*map[string]interface{}, error) {
	connection := shared.Connection()
	if connection == nil {
		return nil, errors.New("No connection to database server")
	}
	var result map[string]interface{}
	collection := connection.DB(variables.DBName).C(collectionName)
	if !bson.IsObjectIdHex(id) {
		return nil, errors.New("Invalid id: " + id)
	}
	err := collection.FindId(bson.ObjectIdHex(id)).One(&result)
	if err != nil {
		return nil, err
	}
	return &result, nil
}
Beispiel #2
0
// Index creates an index on an a collection
func Index(collectionName, key, indexType string) error {
	connection := shared.Connection()
	if connection == nil {
		return errors.New("No connection to database server")
	}
	collection := connection.DB(variables.DBName).C(collectionName)

	setIndex := fmt.Sprintf("$%s:%s", indexType, key)

	// Define the index
	index := mgo.Index{
		Key: []string{setIndex},
	}

	// Apply the index
	return collection.EnsureIndex(index)
}
Beispiel #3
0
// Near reteives records near the given longitude and latitude
func Near(collectionName string, longitude, latitude, radius float64) (*map[string]interface{}, error) {
	connection := shared.Connection()
	if connection == nil {
		return nil, errors.New("No connection to database server")
	}
	collection := connection.DB(variables.DBName).C(collectionName)

	setIndex := fmt.Sprintf("$%s:%s", "2dsphere", "location")

	// Define the index
	index := mgo.Index{
		Key: []string{setIndex},
	}

	// Apply the index
	err := collection.EnsureIndex(index)
	if err != nil {
		log.Println("ERROR creating 2dsphere index", err)
	}

	var found []map[string]interface{}
	err = collection.Find(bson.M{
		"location": bson.M{
			"$nearSphere": bson.M{
				"$geometry": bson.M{
					"type":        "Point",
					"coordinates": []float64{longitude, latitude},
				},
				"$maxDistance": radius,
			},
		},
	}).All(&found)
	if err != nil {
		return nil, err
	}
	result := map[string]interface{}{
		"rows": found,
	}
	return &result, nil
}