Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (47.6k points)

I have a collected named foo hypothetically.

Each instance of foo has a field called last looked at which is a UNIX timestamp since epoch. I'd like to be able to go through the MongoDB client and set that timestamp for all existing documents (about 20,000 of them) to the current timestamp.

What's the best way of handling this?

2 Answers

0 votes
by (106k points)

To update every document on one field this code will be helpful for you:-

Model.update({ 

'type': "newuser" 

}, { 

$set: { 

email: "[email protected]", 

phoneNumber:"0123456789" } 

}, { 

multi: true 

},

function(err, result) { 

console.log(result); 

console.log(err); 

})

0 votes
by (107k points)

In MongoDB, for your problem, you can use the updateMany() function. You can write the following syntax to update multiple documents:

db.foo.updateMany({}, {$set: {lastLookedAt: Date.now() / 1000}})

  • {} is the condition. The empty brackets means that it matches any document

  • {$set: {lastLookedAt: Date.now() / 1000}}- refer this as thisis what you are looking for

If you want to learn more about MongoDB then go through this MongoDB course for more insights.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Sep 4, 2019 in SQL by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...