Search code examples
mongodbmgo

how to search a key of embed object in mgo?


query:=bson.M{"relationship.from": bson.RegEx{"\\d+8.*", ""}}

c.Find(query).All(&users)

above code returns empty set, but the collection looks like:

{"name" : "test","phone": "13xxxx" "relationship":{"from":1982, "to": 1998}}
{"name" : "test2", "phone": "15xxx","relationship":{"from":1981, "to": 1999}}

that will be ok if search phone key, and it is fails in mongodb console :

db.users.find({"relationship.from": /\d+8\d*/})

no matched result??


Solution

  • A regular expression can only match strings, but the field value in these documents are numbers.

    To match these, have a look at the comparison query operators:

    http://docs.mongodb.org/manual/reference/operator/query-comparison/