如何使用mongodb中的查找对单个集合的文档执行相等匹配?
我是MongoDB的新手,我正在尝试做一个平等匹配,但一直未能做到这一点。我有一个“用户”集合,其中包含以下数据:如何使用mongodb中的查找对单个集合的文档执行相等匹配?,mongodb,Mongodb,我是MongoDB的新手,我正在尝试做一个平等匹配,但一直未能做到这一点。我有一个“用户”集合,其中包含以下数据: { uid:"1230" age:20 Name:"Alex" gender:"male" interestedIn:"female" } { uid:"1231" age:23 Name:"Neil" gender:"male" interestedIn:"male" } { uid:"1232" age:20 Name:"
{
uid:"1230"
age:20
Name:"Alex"
gender:"male"
interestedIn:"female"
}
{
uid:"1231"
age:23
Name:"Neil"
gender:"male"
interestedIn:"male"
}
{
uid:"1232"
age:20
Name:"Amy"
gender:"female"
interestedIn:"male"
}
我想要的是找到“性别”等于当前用户“兴趣”的记录,反之亦然。i、 e.当我以用户“Alex”的身份访问时,查询应该只提供“Amy”的记录(因为Amy的性别值等于Alex的“interestedIn”值),而不是Neil的记录。及
当我作为用户“Neil”访问时,不应返回任何数据,因为没有任何男性用户以及对男性感兴趣的用户
我尝试使用$lookup,但它根本不起作用。我很难用$cond操作符来处理这个案子。这是我的密码:
//我也在使用地理空间函数(通过硬编码坐标),但这不是问题所在,没有返回任何内容
db.users.aggregate([{
"$geoNear": {
"near": {
type: "Point",
coordinates: [31.9686, 99.90]
},
"spherical": true,
"distanceField": "distance",
"maxDistance": 500,
"query": {
uid: {
$ne: "1230"
},
age: {
$gt: 18,
$lt: 25
},
{
$lookup:
{
from: "users",
localField: "gender",
foreignField: "interestedIn",
as: "gender_docs"
}
},
limit: 5
}
},
{
"$project": {
location: 0
}
}
]).pretty()
有人能告诉我该怎么做吗
//当前用户为Alex时的预期输出
{
uid:"1232"
age:20
Name:"Amy"
gender:"female"
interestedIn:"male"
}
当当前用户为Neil时,我的预期输出应该为空,因为没有任何其他性别为男性且感兴趣的记录为男性 这里不需要聚合框架和
$lookup
。我希望您的应用程序中存在当前用户的属性(例如,感兴趣的
)
对于您的问题,一个简单的查询是:
db.users.find({
"gender": currentUserInterestedIn,
"_id": { "$ne": currentUserID },
"location": "$near": {
"type": "Point",
"coordinates": [currentUserLat, currentUserLong],
"$maxDistance": 500
},
})
其中,currentUserInterestedIn
应为当前用户感兴趣的实际值,即“男性”
或“女性”
这假设用户位置存储在名为
location
的字段中 您能添加准确的预期输出吗?请尝试localField:“interestedIn”,foreignField:“gender”
@Veeram在我尝试了您提到的方法之后,mongo shell中什么都没有发生。你能帮帮我吗!您可以只在查找阶段尝试代码,看看是否返回任何内容吗?查找代码正确。您如何作为用户Alex访问它pI没有“currentUserInterestedIn”字段,您的代码中是否缺少用于性别值的点运算符?我正在对地理空间查询使用聚合。我也添加了预期的输出!我不知道你说的“点运算符”是什么意思。您也可以使用地理空间查询而不进行聚合。如果您想计算一些内容,则将使用聚合。您的代码有“性别”:currentUserInterestedIn,但我没有任何具有此类名称的键字段。我猜的是“currentUser.InterestedIn”…如果没有聚合,我如何执行上述查询?这样做会不会影响db的性能?就像您在上面的示例查询中添加一些坐标一样,您会将实际的interestedIn
值添加到我的查询中,而不是currentUserInterestedIn
。这只是一个占位符名称,我放进去说“实际值在这里”。好的,谢谢,我会像你说的那样尝试,让你知道一切是否顺利。顺便问一下,如果我不在这里使用聚合,db的性能如何?