我有这样的mongoose.Schema:
User.js:
const mongoose = require('mongoose');
const bcrypt = require('bcrypt-nodejs');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: String,
password: String,
email: String,
});
module.exports = mongoose.model('users', UserSchema, 'users');
product.js:
const mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
userid: {type:String, required: true},
product_name: {type:String, required: true}
});
ProductSchema.plugin(mongoosePaginate);
module.exports = mongoose.model('products', ProductSchema, 'products');
方式:
exports.selectUsersProductsCount = function (req, res, next) {
Product.aggregate([
{"$group" : {_id:{userid:"$userid" }, count:{$sum:1} } }
],
function(err, result) {
if(err){ res.status(400).json({ success: false, message:'Error processing request '+ err }); }
res.status(201).json({
success: true,
data: result
});
console.log(result);
})
}
结果:
[ { _id: { userid: '5ab655bbb94733156c438112' }, count: 3 },
{ _id: { userid: '5ab425c6f5bff145304092f7' }, count: 1 } ]
我希望同时显示username
字段。我不知道如何使用join
。计算正确,但不显示用户名字段。
如何更正要显示的aggregate
方法:
用户ID,用户名,计数
[ { _id: { userid: '5ab655bbb94733156c438112', username: 'Jon Alon' }, count: 3 },
{ _id: { userid: '5ab425c6f5bff145304092f7', username: 'Jonson Con' }, count: 1 } ]
示例数据:
产品
{
_id:O bjectId(5ab7da972ade533790268f47),
userid:"5ab655bbb94733156c438112",
product_name:"gs",
__v:0
},{
_id: ObjectId(5ab7daa92ade533790268f48),
userid:"5ab655bbb94733156c438112",
product_name:"dg",
__v:0
}
用户
{
_id: ObjectId(5ab655bbb94733156c438112),
username: "rrrr",
email:"rrrr",
__v:0
}
答案 0 :(得分:1)
您必须使用$ lookup函数来实现这一目标,但您需要在两个集合之间具有一些共同属性。 您需要在UserSchema或其他一些属性上添加userId,以便您可以加入"
在您的示例中,您可以尝试
db.product.aggregate([ {$lookup:{ from: "user", localField: "ObjectId(userid)", foreignField: "ObjectId(_id)", as: "username" }}, {"$group" : {_id:{userid:"$userid", username : "$username" }, count:{$sum:1} } } ])
答案 1 :(得分:0)
解决方案
products.aggregate([
{$lookup:{
from: "users",
localField: "ObjectId(userid)",
foreignField: "ObjectId(_id)",
as: "users"
}},
{ "$group" :
{
_id: { userid: "$userid" },
name: { $last: "$users.username" } ,
count: { $sum: 1 }
}
}, {$sort: {"_id.userid": 1}}
], function(err, result) {
console.log(result);
if(err){ res.status(400).json({ success: false, message:'Error processing request '+ err }); }
res.status(201).json({
success: true,
data: result
});
}
);
}
返回:
[ { _id: { userid: '5ab425c6f5bff145304092f7' },
name: [ 'cccc', 'rrrr', 'zzzz' ],
count: 3 },
{ _id: { userid: '5ab655bbb94733156c438112' },
name: [ 'cccc', 'rrrr', 'zzzz' ],
count: 1 },
{ _id: { userid: '5aba7e8c045115340496becd' },
name: [ 'cccc', 'rrrr', 'zzzz' ],
count: 2 } ]