jeroen / mongolite

Fast and Simple MongoDB Client for R
https://jeroen.github.io/mongolite/
284 stars 64 forks source link

missed possibility to use aggregation pipeline in $update #260

Open eutanatos opened 6 months ago

eutanatos commented 6 months ago

According Mongodb manual I can use in either document {} or pipeline [] and it can lead to different results:

document

db.Collection.insertMany( [
{"_id" : 1, "links" : [ {link_1: "url1", link_2: "url2"} ] },
{"_id" : 2, "links" : [ {link_1: "url3", link_2: "url4"} ] }
] )

db.Collection.updateMany( {}, { "$set": {"links: {"$arrayElemAt": ["$links", 0]}} } )

db.Collection.findOne( {} )
// {_id: 1, links: {'$arrayElemAt': ['$links', 0 ] } }

pipeline

db.Collection.insertMany( [
{"_id" : 1, "links" : [ {link_1: "url1", link_2: "url2"} ] },
{"_id" : 2, "links" : [ {link_1: "url3", link_2: "url4"} ] }
] )
db.Collection.updateMany( {}, [{ "$set": {"links: {"$arrayElemAt": ["$links", 0]}} }] )

db.Collection.findOne( {} )
// {_id: 1, links: { link_1: "url1", link_2: "url2" } }

Mongolite accepts only document form of update request with consequent loose of possibility of mongo functions usage:

mongo_collection$update('{}', update = '{"$set": {"links": { "$arrayElemAt": ["$links", 0] } } }', multiple = TRUE)
mongo_collection$find('{}')
# {_id: 1, links: {'$arrayElemAt': ['$links', 0 ] } }

mongo_collection$update('{}', update = '[{"$set": {"links": { "$arrayElemAt": ["$links", 0] } } }]', multiple = TRUE)
# Error: Invalid JSON object: [{"$set": {"links": {$arrayElemAt: ["$links", 0]} } }]

I know it can be overrided by $aggregation with merge in same collection, but can you add this functionality?