Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do text search in mgo?

Tags:

mongodb

go

mgo

I'm trying to search "efg" in field named "abc"

c.Find(bson.M{"$text": bson.M{"abc": "efg"}})

c is Collection object. I'm not getting any result. What am I doing wrong?

like image 796
Chakradar Raju Avatar asked May 20 '14 13:05

Chakradar Raju


2 Answers

You are generating {$text:{abc:"efg"}}, but your query should look like this: {$text:{$search:"efg"}}

So try updating your code to:

c.EnsureIndexKey("abc")
c.Find(bson.M{"$text": bson.M{"$search": "efg"}})

Keep in mind that to search with $text, you need to specify an index. Check out this document that explains how to use it: http://docs.mongodb.org/manual/reference/operator/query/text/

like image 173
Goodwine Avatar answered Sep 29 '22 04:09

Goodwine


use $regex(option i for case insensitive)
example:

c.Find(bson.M{"abc": &bson.RegEx{Pattern: "efg", Options: "i"}})
like image 43
thesyncim Avatar answered Sep 29 '22 03:09

thesyncim