如何使用 Mongoose 从 MongoDB 中的两个集合关系中查找计数
How to find count from two collections relationship in MongoDB using Mongoose
我想显示特定用户 (_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大数据好,关系不好
我想显示特定用户 (_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大数据好,关系不好