简体   繁体   中英

MongoDB update multiple collections

My mongo db contains following collections name like

10.9.40.46
10.9.40.47
10.9.40.48
10.9.40.49
10.9.40.50
10.9.40.51
10.9.40.52

In all collections having N numbers of documents and every documents had common key name as "status" by default all documents had "status" 1, When I update my collections to change "status" 1 to 0 I use following query

 db.getCollection("10.9.40.46").update({"status":1},{$set:{"status":0}},false,true)

The above query work fine but, I want update all my collections then I pass my collections name to query manually, So there is any concepts in MongoDB that I used database and update all collections documents in that database using single query or something like that? I also used looping to read all collections and update documents but I it takes long time because of large number of collections.

No, there is no API to perform the same operation on multiple collections with a single command. That's because you normally don't use collections the way you use them. Collections are used to group documents of the same type, not for grouping them based on content and/or key.

The normal way to organize the documents you have would be to put them all in one collection, add a field for the IP address to each document and create an index on the ip-field for faster lookup.

you can use for loop for the same.

var collection='10.9.40.'
var count=46;
var n=46;
var url='';
for(i =0;i<7;i++){
url="";
n=46+i;
url=count+n;
db.getCollection(url).update({"status":1},{$set:
{"status":0}},false,true)
}

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