I am working on a mongo query in golang using mgo to update a child element property
{
"_id" : ObjectId("5b64a0d3931653c36bcaf0b5"),
"quantity" : 2,
"product" : "ABC",
"children" : [
{ "jiraId":"100"
"isBlocked" : true,
"blockedMessage" : "Error occurred: TRACEID",
"serialNo" : "abc123",
"token" : "",
}
]
}
The query I am using in below
Update(repository.MongoSpec{Selector: bson.M{"children": bson.M{"$elemMatch": bson.M{"jid": "100"}}}, Query: bson.M{"children": bson.M{"$set": fields}}})
Below is the update function
s := spec.(MongoSpec).Selector
q := spec.(MongoSpec).Query
err := session.
DB(repo.config.databaseName).
C(repo.collectionName).
Update(s, q)
MongoSpec struct
type MongoSpec struct {
Selector interface{}
Query interface{}
}
The above query throws an error as below
The dollar ($) prefixed field '$set' in 'children.$set' is not valid for storage.
May I know what is wrong with the query.
I think you are not usign correctly $set, check this example and adapt it to your language:
getCollection('collectionName').findOneAndUpdate(
{"children.jiraId":100}, //Search the subdocument
{$set:{"children.$.isBloqued":false}}}, //update the subdocument
)
Update(repository.MongoSpec{Selector: bson.M{"children": bson.M{"$elemMatch": bson.M{"jid": "100"}}}, Query: bson.M{"children": bson.M{"$set": fields}}})
If you specify only a single query condition in the $elemMatch expression, you do not need to use $elemMatch
. Just use dot notation to access the elements of an array or embedded document. For example in mongo shell:
db.collection.update(
{"children.jid": "100"},
{"$set":{"children.$.field":"foobar"}})
Notice that the update operator $set is specified first before any fields. See also Set Fields in Embedded Documents.
Also, please note the additional $
between the array field children
and field
. This is a positional $ operator to identifies an element in an array to update without explicitly specifying with position of the element in the array. For example, if you have two elements in children
only apply the update operator to the element matching jid="100"
.
Similarly using mgo.v2
, you can specify:
err = c.Update(
bson.M{"children.jid":"100"},
bson.M{"$set":bson.M{"children.$.field":"foobar"}}
)
Worth mentioning that mgo.v2
has been discontinued, if you're starting a new project use mongo-go-driver to support MongoDB v3.2 and above.