查找尚未邀请任何用户的用户 [英] Find users who has not invited any user

查看:40
本文介绍了查找尚未邀请任何用户的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想找到一个没有通过单个查询(使用汇总)邀请任何用户的用户.

I want to find those users who has not invited any user by a single query (using aggregate).

例如:我在数据库中有4个用户

for Example : I have 4 users in DB

{
    "_id" : ObjectId("581a18d41b6c5c752f11c87a"),
    "name": "aaa",
    "invitedBy": ObjectId("5808f53d28c14ee470856d8b")
},

{
    "_id" : ObjectId("581a1a671b6c5c752f11c87b"),
    "name": "bbb",
    "invitedBy": ObjectId("581a18d41b6c5c752f11c87a")
},

{
    "_id" : ObjectId("581a1a671b6c5c752f11c87c"),
    "name": "ccc",
    "invitedBy": ObjectId("581a18d41b6c5c752f11c87a"),
},

{
    "_id" : ObjectId("581a1a671b6c5c752f11c87d"),
    "name": "ddd",
    "invitedBy": ObjectId("581a1a671b6c5c752f11c87b"),
}

这里

1- aaa邀请了bbb和ccc用户

1- aaa invited bbb and ccc user

2- bbb邀请了ddd用户

2- bbb invited ddd user

3-但ccc和ddd用户未邀请任何人

3- but ccc and ddd user not invited any one

所以我想给 ccc ddd 个用户

如果可以的话,最好使用聚合,因为我需要对选定的数据执行一些操作.

it would be better if can by using aggregate because I need perform some operation on selected data.

推荐答案

您可以使用 $lookup 运算符,以对集合本身执行左连接.

You can use the $lookup operator to perform a left join to the collection itself.

尚未发送任何邀请的用户是邀请数组为空的用户.要仅检索那些用户,只需在 $match 阶段使用 $exists 运算符和数字数组索引.

The users who have not sent any invitation are those with empty invitation array. To retrieve only those users, simply filter the documents in a $match stage using the $exists operator and numeric array indexing.

db.users.aggregate(
    [
        { "$lookup": { 
            "from": "users", 
            "localField": "_id", 
            "foreignField": "invitedBy", 
            "as": "invitation"
        }}, 
        { "$match": { "invitation.0": { "$exists": false } } }
    ]
)

产生:

{
    "_id" : ObjectId("581a1a671b6c5c752f11c87c"),
    "name" : "ccc",
    "invitedBy" : ObjectId("581a18d41b6c5c752f11c87a"),
    "invitation" : [ ]
}
{
    "_id" : ObjectId("581a1a671b6c5c752f11c87d"),
    "name" : "ddd",
    "invitedBy" : ObjectId("581a1a671b6c5c752f11c87b"),
    "invitation" : [ ]
}

这篇关于查找尚未邀请任何用户的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆