My find query looks like the following:
bson.M{"_id": oId, "items": bson.M{"$elemMatch": bson.M{"id": theId, "active": true}}}
(where theId
is the object id from a method)
What I'm trying to do is to select a document with the matching id
and where active
is set to true
{
"_id" : ObjectId("5ca0e44acb216df65405dc5f"),
"items" : {
"0" : {
"id" : ObjectId("5c9fbb25e86deef65491c321"),
"active" : true
},
"1" : {
"id" : ObjectId("5c9fbb57cb216df65405dc5c"),
"active" : false
},
"2" : {
"id" : ObjectId("5c9fbb65cb216df65405dc5d"),
"active" : false
}
},
}
But no matter how I do it, it never finds any documents. How can this be done?
Edit: Added my Go code.
func CountRows(find interface{}) int {
session := database.GetMongoSession()
defer session.Close()
c := session.DB(config.Settings.Database.Name).C("list")
count, err := c.Find(find).Count()
if err != nil {
log.Fatal(err)
}
return count
}
func IsActive(oId bson.ObjectId, theId bson.ObjectId) bool {
if CountRows(bson.M{"_id": oId, "items": bson.M{"$elemMatch": bson.M{"id": theId , "active": true}}}) > 0 {
return true
}
return false
}
It always returns false because it can't find any documents.
If you own the database I would suggest restructuring your data to look like this:
{
"_id" : ObjectId("5ca0e44acb216df65405dc5f"),
"items" : [
{
"id" : ObjectId("5c9fbb25e86deef65491c321"),
"active" : true
},
{
"id" : ObjectId("5c9fbb57cb216df65405dc5c"),
"active" : false
},
{
"id" : ObjectId("5c9fbb65cb216df65405dc5d"),
"active" : false
}
]
}
Then you can use the MongoDB's own documentation: Query an Array of Embedded Documents methods.