F
F
ff3446r3e2021-11-24 15:25:12
MongoDB
ff3446r3e, 2021-11-24 15:25:12

How to remove an element from an array in MongoDB?

Remove element from expenses array

{"_id":{"$oid":"12"},
"chatID":{"$numberInt":"12"},
"expenses":[
   ​{"category":"food","amount":{"$numberDouble":"12.0"}},
   ​{"category":"food","amount":{"$numberDouble":"14.0"}}],
"income":[]}

I tried the method below but it didn't work.
update := bson.M{"$pull": bson.M{"expenses": bson.D{{"category", "food"}, {"amount", 12}}}}
c.Coll.UpdateOne(context.TODO(), bson.M{"chatID": chatID}, update)

In the end I need it to turn out like this
{"_id":{"$oid":"12"},
"chatID":{"$numberInt":"12"},
"expenses":[
   ​{"category":"food","amount":{"$numberDouble":"14.0"}}],
"income":[]}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Leonid Nikolaev, 2021-11-24
@nikonor

https://github.com/tidwall/sjson
well, to the heap https://github.com/tidwall/gjson

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question