简体   繁体   中英

How to find count from two collections relationship in MongoDB using Mongoose

I want to display list files of particular user (_id: 876896) with their click counts as below:

Sr. No. | File Name | Click Count

Below is the sample schema I am using:

var clicks = mongoose.Schema({
 file_id   : String,
 IP    : String
});

var files = mongoose.Schema({
 filename   : String,
 owner    : {type:mongoose.Schema.ObjectId, ref:'users'},
});

How effectively this can done.

You can do it in two step, first get all files that refer to the users you want data for. Then, get alls clicks that are related to files you read. There is no INNER_JOIN in mongodb

Little example :

     files.find({
           owner: {
              $in: usersIdsArray // [_id, _id...] ids of all users
           },
        }).then((ret = []) => {
            // Here ret is array of files
            if (!ret.length) // There is no files matching the user
            return clicks.find({
                 file_id: {
                     $in: Array.from(ret, x => x._id.toString()),
                     // build an array like [_id, _id, _id...]
                 },
            });
        }).then((ret = []) => {
            // Here you have all clicks items
        });

I also recommend to use embedded schema instead of multiple collections:

var clicks = mongoose.Schema({
 file_id: String,
 IP: String
});

var files = mongoose.Schema({
 filename: String,
 owner: {type:mongoose.Schema.ObjectId, ref:'users'},
});

turn into:

var files = mongoose.Schema({
   filename: String,
   owner: {type:mongoose.Schema.ObjectId, ref:'users'},
   clicks: [String], // With String your IP
});

MongoDB is good when it comes to big data, but not that good in relations.

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