简体   繁体   中英

Running batch operations in MongoDB/ Robo3t

I have a list of users in a file and I want to update their record in a collection.

ie

db.getCollection('users').update({username: "<a user>"}, { $set: { <set some values here> }})

How can I feed a list of users into this command or something similar in Robo 3T or from a terminal command line?

The following from the command line seems the easier options:

Option A) generate the update queries on the fly from the list of users and send to the mongo shell:

cat file.csv | awk '{ print("db.users.update({user:\""$1"\"},{ $set:{x:1} }) ")   }' | mongo 

Option B) mongoimport

Step 1) Import the user list to the database in temporary collection:

 mongoimport --type csv -d test -c usersToUpdate --headerline  file.csv

file.csv:

 userlist
 John
 Donald
 Jeny

Step 2) As soon as the collection is imported you can do as follow:

  db.usersToUpdate.find({},{_id:0,userlist:1}).forEach(function(theuser){      db.users.update({username: theuser.userlist}, { $set: { <set some values here> }}); print(theuser+" record updated successfully");      })

Step 3) Finally you can clean the temporary usersToUpdate collection with:

  db.usersToUpdate.drop() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM