Remove JSON objects which have specific field type from JSON array field in MongoDB document -
given collection documents have array field containing json objects (key-value pairs) e.g.:
{ ..., arr : [{key: val}, {key : numberlong(100)}]}
after update, same document should like:
{ ..., arr : [{key: val}]}
the document in arr field:
{key : numberlong(100)}
should removed.
is possible mongodb $ operators? tried use following code no avail:
db.coll.find({}).foreach( function(doc) { var objs = doc.arr; for(var = objs.length; i--;){ if (typeof(objs[i].ts) == numberlong) objs.splice(i,1); } db.coll.save(doc); })
i suppose looking remove data array this:
{ "field" : "aaa", "list" : [ "aaa", numberlong(123), "bbb", numberlong(456) ] }
you can using $pull
takes query expression it's argument
db.collection.update({ },{ "$pull": { "list": {"$type": 18 } } })
edit
since question has changed, still doesn't change in answer though:
{ "list" : [ { "key" : "val" }, { "key" : numberlong(100) }, { "key" : numberlong(123) } ] }
and same query:
db.list.update({ }, { "$pull": { "list": { "key": {"$type": 18 } } } })
then numberlong()
types removed.
add { "multi": true }
want happen on multiple documents.
so uses $type
in order match "numberlong" elements, 64-bit integers. values each "type" on manual page.
the positional $
operator not suit here as:
it not valid argument can used remove elements.
even used
$set
, "setting" valuefalse
, match first element matched in array. @ rate not removing item , still need use pull.
also, javascript method, typeof()
looking not return other object
javascript implementation. have test in way.
but don't. using native update methods best way.
Comments
Post a Comment