Mongodb collection has a array type and members are string. I want to get if a member of array starts with "abc". How can I write a filter for that?
collection example:
{
_id:"1",
name:"",
data:["abcdfd","gfgqqdg","abcfdgsfg"]
},
{
_id:"2",
name:"",
data:["abcdfd","gfgqqdg","ghfdgsfg"]
},
{
_id:"3",
name:"",
data:["hjhfdfd","gfgqqdg","afdgsfg"]
}
So, find query must return first and second because the "data" has members start with "abc".
CodePudding user response:
You can try using $regex
as shown below:
db.collection.find({
"data": {
"$regex": "/^abc*/"
}
})
Also checkout: How to write mongodb query for regex in GoLang using bson?
CodePudding user response:
In MongoDB, you can match any element in array of data using the following syntax:
db.collection.find({ "data": "abcdfd" })
To find documents where any of the array values starts a string "abc", you can use any of the queries:
db.collection.find({ "data": "^abc" })
db.collection.find({ data: { $regex: "^abc" }})
db.collection.find({ data: { $regex: /^abc/ }})
Where, ^
(caret) is a special character used with regular expressions; matches the starting position of a string.
The Golang version of the query:
var results []bson.M
filter := bson.D{{ "data", bson.D{{ "$regex", "^abc" }}}}
cur, err := collection.Find(context.TODO(), filter)
if err != nil {
log.Fatal(err)
}
if err = cur.All(context.TODO(), &results); err != nil {
log.Fatal(err)
}
for _, result := range results {
fmt.Println(result)
}