首页 > mongodb如何进行子查询

mongodb如何进行子查询

用户collection,我是这么设计的:

User {
    uid: xx,
    name: xxx,
    description: xxxx,
    follow: ["uid1","uid2","uid3",...]
}

为了列出某个用户follow的所有人列表,我该如何写查询语句呢?

<uid1, name1, description1>
<uid2, name2, description2>
...

不要仅仅把mongodb当做一个schemeless的sql数据库,mongodb是没有子查询和跨表查询这个概念的。

按照你的描述,如果你想要获取某个用户follow的所有人的详细信息列表,一种做法是把这些用户的所有信息都存到User里面:

User {
    uid: xx,
    name: xxx,
    description: xxxx,
    follow: ["uid1": {'name': 'xxx', 'description': 'desc1'},"uid2": {'name': 'zzz', 'description': 'desc2'},...]
}

或者你使用二次查询,在代码里面再查一次

db.User.find({'uid':{'$in': [uid1, uid2, uid3]}});
【热门文章】
【热门文章】