有两个集合,第一个是名为firstcollection的集合,其中包含以下元素
{ uid:12345, pid:777, comment="first" }
和其他元素,称为such集合,其中包含以下元素
{ uid:12345, extra:17 }
如何才能获得通过uid连接两个集合的输出,同时满足两个集合中的条件(例如,第一个集合中存在注释字段,第二个集合中的额外字段大于15 )。
现在,我试着这样做:
var x = db.firstcollection.find({comment:{$exists:true}})
db.secondcollection.aggregate({
$lookup:
{
from: "x",
localField: "uid",
foreignField: "uid",
as: "aggregation"
}
})但我完全不确定我是否走对了,也不知道如何查询secondcollection,这样它才能满足我前面提到的条件。
发布于 2018-06-23 09:31:14
@wazowski...{userinfo.name“$unwind”:$userinfo“$project”},{“$project”:{“text”:1,1,“date”:1,“userinfo.name”:1,“userinfo.country”:1);
如果你是个乞讨者,那就很清楚地为你解释了…
db.users.aggregate([ //与user_info表连接{ $lookup:{ from:" userinfo ",//其他表名localField:"userId",//用户表字段名称foreignField:"userId",//用户信息表字段名为:"user_info“//用户信息表别名} },{ $unwind:"$user_info”},// $unwind用于获取对象中的数据或仅用于一条记录//与user_role表连接{ $lookup:{ from:"userrole",localField:"userId",foreignField:"userId",as:"user_role“} },{ $unwind:"$user_role”},//在这里定义一些条件{ $match:{ $and:{" userName“:"admin"} } },//定义需要拉取哪些字段{ $project:{ _id : 1,email : 1,userName: 1,userPhone:"$user_info.phone",role:"$user_role.role",}} ]);
这将产生如下结果:
{ "_id“:ObjectId("5684f3c454b1fd6926c324fd"),"email”:"admin@gmail.com","userName“:"admin","userPhone”:"0000000000","role“:"admin”}
https://stackoverflow.com/questions/50997004
复制相似问题