Reputation: 148
I have this aggregation command and need to overwrite the current documents;
db.collection.aggregate([
{
$project: {
class: "Apples",
imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
}
}
])
Collection:
{
id:...
class:"Apples"
imageUrl:"..."
}
There are multiple documents that need to be updated. this is what i currently have appended to the above command but its not working.
.forEach( doc => db.product.updateOne( { _id: doc._id }, { $set: { imageUrl: doc.imageUrl } } ) )
Thanks in advance!
Upvotes: 1
Views: 348
Reputation: 49945
You can either run $out (replaces entire existing collection with aggregation result):
db.collection.aggregate([
{
$project: {
class: "Apples",
imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
}
},
{ $out: "collection" }
])
or new $merge operator ("merges" aggregation results with existing documents):
db.collection.aggregate([
{
$project: {
class: "Apples",
imageUrl: { $substr: [ "$imageUrl", 0, { $indexOfBytes: [ "$imageUrl", "\n" ] } ] }
}
},
{ $merge: { into: "collection", on: "_id", whenMatched: "replace", whenNotMatched: "insert" } }
])
Upvotes: 3