我正在执行 mongodb 查询,或者我正在对 SQL 数据库使用 LEFT JOIN。
这是一个配置文件的文件:
{
"_id" : ObjectId("5bd22f28f77cfb1f6ce503ca"),
"search" : "flarize",
"name" : "flarize",
"email" : "[email protected]",
"password" : "$2a$10$eYeOtEkEUyD7TFkjKvhZOuSSpvBolkL17TrPHuoHhOT8JrsQR0UKW",
"color" : 0,
"profil" : "",
"banner" : "",
"desc" : "",
"date" : 1540501286109,
"friend" : [
{
"id" : ObjectId("5bd19a92da24674fdabd26b6")
}
],
"groupes" : [ ]
}
我目前正在使用此请求:
db.users.find({search: /f/}).limit(20);
这个查询只是根据正则表达式给出了配置文件。
我可能想要更多,如果调用此查询的人的 ID 出现在朋友部分中,那么我们添加:
is_friend: true
否则添加:
is_friend: false
编辑 :
对于这个查询,我们有:
调用请求的人的 id,以及尝试知道此 id 是否存在于朋友字段中的人的 id。
编辑
我试过这个但不起作用,返回false。
herdb.users.aggregate([{$match:{"search":"flarize"}},
{$project:
{search: 1, name: 1, color: 1, profil: 1, banner: 1, desc: 1, date: 1, friend:10, groupes:10,
is_friend:
{$cond:[
{$eq:["$friend.id", ObjectId("5bd19a92da24674fdabd26b6")]},
true,
false]
}
}
}
]).pretty();
感谢你们对我的帮助。
$unwind
在匹配之前为朋友使用id
$eq
不适用于数组。
db.getCollection('tests').aggregate([
{ $match: {"search":"flarize"} },
{ $unwind: "$friend"},
{ $project:{
search: 1, name: 1, color: 1, profil: 1, banner: 1, desc: 1, date: 1, friend:10, groupes:10,
is_friend: { $cond: [
{ $eq :["$friend.id", ObjectId("5bd19a92da24674fdabd26b6")]}, true, false ]}
}
}
]);
输出:
/* 1 */
{
"_id" : ObjectId("5bd22f28f77cfb1f6ce503ca"),
"search" : "flarize",
"name" : "flarize",
"color" : 0,
"profil" : "",
"banner" : "",
"desc" : "",
"date" : NumberLong(1540501286109),
"friend" : {
"id" : ObjectId("5bd19a92da24674fdabd26b6"),
"id" : ObjectId("5bd19a92da24674fdabd26b4"),
"id" : ObjectId("5bd19a92da24674fdabd26b2"),
"id" : ObjectId("5bd19a92da24674fdabd26b1")
},
"groupes" : [],
"is_friend" : true
}
如果您想将其friend
返回到数组列表:
db.getCollection('tests').aggregate([
{ $match: {"search":"flarize"} },
{ $unwind: "$friend"},
{ $project:
{
search: 1, name: 1, color: 1, profil: 1, banner: 1, desc: 1, date: 1, friend:10, groupes:10,
is_friend: { $cond: [
{ $eq :["$friend.id", ObjectId("5bd19a92da24674fdabd26b6")]}, true, false ]}
}
},
{$group : {
_id: "$_id",
search : {$first: "$search"},
name : {$first: "$name"},
color : {$first: "$color"},
profil : {$first: "$profil"},
banner : {$first: "$banner"},
desc : {$first: "$desc"},
date : {$first: "$date"},
groupes : {$first: "$groupes"},
friend : {$push: "$friend"},
is_friend: {$first: "$is_friend"}
}}
])
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句