![](/img/trans.png)
[英]How simultaneously find documents and get their count from mongodb using mongoose
[英]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在大數據方面很好,但在關系方面卻不是很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.