Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

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.

i.e

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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}, { $set: { <set some values here> }}); print(theuser+" record updated successfully");      })

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

  db.usersToUpdate.drop() 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...