I am trying to update an array in my mongo document. Want to switch out the value. within the favorited_by array. Want to switch out 5170049 for 81952455 and I am using this command in MongoShell but receiving this error
MongoShell command
db.messages.updateOne({_id: "140449331274573645", favorited_by: "5170049"}, {$set: {{"favorited_by.$": "81952455"}})
Error
Error: clone(t={}){const r=t.loc||{};return e({loc:new Position("line"in r?r.line:this.loc.line,"column"in r?r.column:...<omitted>...)} could not be cloned.
at Object.serialize (node:v8:332:7)
at u (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:594983)
at postMessage (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:595591)
at i (/Applications/MongoDB Compass.app/Contents/Resources/app.asar.unpacked/node_modules/@mongosh/node-runtime-worker-thread/dist/worker-runtime.js:1917:600488)
Document
{
"_id": "140449331274573645",
"attachments": [],
"avatar_url": "https://test",
"created_at": 1404493312,
"favorited_by": [
"11666391",
"5170049"
],
"group_id": "12345",
"name": "John Smith",
"sender_id": "19187160",
"sender_type": "user",
"source_guid": "android-a6ce72e8-79a7-4714-8ede-4741c141047f",
"system": false,
"text": "sample",
"user_id": "123456",
"pinned_at": null,
"pinned_by": "",
"create_date": {
"$date": {
"$numberLong": "1660760105066"
}
},
"date_time": {
"$date": {
"$numberLong": "1404478912000"
}
}
}
CodePudding user response:
Going off of @Charchit Kapoor's clue in the comments, the problem is a minor syntax issue. The command posted in the question has:
... {$set: {{"favorited_by.$" ...
It's the double {{
that is the problem. Removing one of them (which is similarly absent in the playground example from the comments) resolves the issue:
>db.foo.updateOne({_id: "140449331274573645", favorited_by: "5170049"}, {$set: {{"favorited_by.$": "81952455"}})
Error: clone(t={}){const r=t.loc||{};return e({loc:new Position("line"in r?r.line:this.loc.line,"column"in r?r.column:...<omitted>...)} could not be cloned.
>db.foo.updateOne({_id: "140449331274573645", favorited_by: "5170049"}, {$set: {"favorited_by.$": "81952455"}})
{ acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0 }
>db.foo.findOne({},{favorited_by:1})
{ _id: '140449331274573645',
favorited_by: [ '11666391', '81952455' ] }