简体   繁体   中英

Zipping two collections in mongoDB

Not a question about joins in mongoDB

I have two collections in mongoDB, which do not have a common field and which I would like to apply a zip function to (like in Python, Haskell). Both collections have the same number of documents.

For example: Let's say one collection ( Users ) is for users, and the other ( Codes ) is of unique randomly generated codes.

Collection Users:

    { "_id" : ObjectId(""), "userId" : "123"}
    { "_id" : ObjectId(""), "userId" : "456"}

Collection Codes:

    { "_id" : ObjectId(""), "code" : "randomCode1"}
    { "_id" : ObjectId(""), "code" : "randomCode2"}

The desired output would to assign a user to a unique code. As follows:

Output

    { "_id" : ObjectId(""), "code" : "randomCode1", "userId" : "123"}
    { "_id" : ObjectId(""), "code" : "randomCode2", "userId" : "456"}

Is there any way of doing this with the aggregation pipeline?

Or perhaps with map reduce? Don't think so because it only works on one collection.

I've considered inserting another random id into both collections for each document pair, and then using $lookup with this new id, but this seems like an overkill. Also the alternative would be to export and use Python, since there aren't so many documents, but again I feel like there should be a better way.

Unlike relational database in MongoDB you doing JOIN stuff at the app level (so it will be easy to horizontal scale the database). You need to do that in the app level.

I would do something like this to get the records from collection 1 & 2 and merge the required fields into single object.

You have already confirmed that number of records in collection 1 and 2 are same.

The below code will loop through the cursor and map the required fields into one object. Finally, you can print the object to console or insert into another new collection (commented the insert).

var usersCursor = db.users.find( {  } );
var codesCursor = db.codes.find( {  } );
while (usersCursor.hasNext() && codesCursor.hasNext()) {   
   var user = usersCursor.next();
   var code = codesCursor.next();  
   var outputObj = {};
   outputObj ["_id"] = new ObjectId();
   outputObj ["userId"] = user["userId"];
   outputObj ["code"] = code["code"];
   printjson( outputObj);
   //db.collectionName.insertOne(outputObj);
}

Output:-

{
    "_id" : ObjectId("58348512ba41f1f22e600c74"),
    "userId" : "123",
    "code" : "randomCode1"
}
{
    "_id" : ObjectId("58348512ba41f1f22e600c75"),
    "userId" : "456",
    "code" : "randomCode2"
}

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