0

Can I create a query, something like this below

db.getCollection('walkins.businesses').update(
    {$and:[{"loyaltyModule.isPublished": true},{"loyaltyModule.publishAt": {"$eq":null}}]},
    {$set : {"loyaltyModule.publishAt":"this.loyaltyModule.creationAt"}}, {multi:true}
    )

to set value of creationAt as publishAt using update query directly where creationAt is already in collection.

Can I set the value of publishAt using another field creationAt in the same document?

chridam
  • 100,957
  • 23
  • 236
  • 235
Foram Sojitra
  • 391
  • 9
  • 19

1 Answers1

2

With Aggregate

The best way to do this is to use the aggregation framework to compute our new field. using the $addFields and the $out aggregation pipeline operators.

db.getCollection('walkins.businesses').aggregate(
    [
        {$match : {$and:[{"loyaltyModule.isPublished": true},{"loyaltyModule.publishAt": {"$eq":null}}]}},

        { "$addFields": { 
            "loyaltyModule.publishAt":"loyaltyModule.creationAt"
        }},
        { "$out": "collection" }
    ]
)

Note that this does not update your collection but instead replace the existing collection or create a new one. Also for update operations that require "type casting" you will need client side processing, and depending on the operation, you may need to use the find() method instead of the .aggreate() method

With Iteration of cursor

you can iterate the cursor and update

db.getCollection('walkins.businesses').find({$and:[{"loyaltyModule.isPublished": true},{"loyaltyModule.publishAt": {"$eq":null}}]}).forEach(function(x){
    db.getCollection('walkins.businesses').update({_id : x._id },
                {$set : {"loyaltyModule.publishAt": x.loyaltyModule.creationAt}},
                {multi:true}
    )
})

here, you can't update multiple records at one update query due to update happening by matching with _id field

Murugan Perumal
  • 975
  • 5
  • 15