我想显示特定用户(_id: 876896)的列表文件,其点击计数如下:
Sr. No. | File Name | Click Count
下面是我使用的示例模式:
var clicks = mongoose.Schema({
file_id : String,
IP : String
});
var files = mongoose.Schema({
filename : String,
owner : {type:mongoose.Schema.ObjectId, ref:'users'},
});
如何有效地做到这一点
您可以分两步完成,首先获取指向您想要的用户的所有文件。然后,获取与所读文件相关的所有点击。mongodb中没有INNER_JOIN
:
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
});
我还建议使用嵌入式模式而不是多个集合:
var clicks = mongoose.Schema({
file_id: String,
IP: String
});
var files = mongoose.Schema({
filename: String,
owner: {type:mongoose.Schema.ObjectId, ref:'users'},
});
变成:
var files = mongoose.Schema({
filename: String,
owner: {type:mongoose.Schema.ObjectId, ref:'users'},
clicks: [String], // With String your IP
});
MongoDB在大数据方面很好,但在关系方面就不那么好了。