【问题标题】:Using "$and" and "$in" together一起使用“$and”和“$in”
【发布时间】:2016-09-19 14:32:40
【问题描述】:

我有一个集合friends 用于存储所有朋友,并具有以下字段

id , userid,friendid

我有一个集合notes,它存储用户注释并具有以下字段

id, userid, ownerid, privateorpublic

规则是用户只能看到他/她创建的笔记或他/她的朋友创建的笔记或公开的笔记

为了获取该信息,我正在以这种方式编写查询。首先,用逗号分隔我朋友的所有 id。我不知道如何编写查询以返回逗号分隔的值,但我希望下面的这个查询将通过给定的 id 返回用户的所有文件:

db.friends.find({ { friendid: { userid: 'jhdshh37838gsjj' } }

然后获取由朋友创建的笔记或公共笔记或属于用户的笔记

db.notes.find({ownerid:'jhdshh37838gsjj', privateorpublic:'public',{ $in: [ "3ghd8e833", "78hhyaysgd" ] }

我是 MongoDB 的新手。我的查询对吗?

【问题讨论】:

    标签: mongodb


    【解决方案1】:

    查找查询语法:db.collection.find({queryFieldName: queryFieldValue}, {requiredFieldName: 1, NotRequiredFieldName: 0})

    因此,翻译第一个查询时,您会得到“从朋友集合朋友那里获取所有文档,其中friendId 等于字符串{'userId':'Id'}”,这是不需要的。

    查询“获取用户 ID jhdshh37838gsjj 的所有朋友 ID,并且不在结果中打印任何其他内容”:db.collection.find({userId:'jhdshh37838gsjj'}, {friendId:1, _id:0})

    但是,这不会以逗号分隔值的形式给出输出。你会得到如下输出(因为每个文档都是一个独立的对象):

    {friendId: 1}
    {friendId: 2}
    

    $in 需要数组作为输入,而不是逗号分隔值。要为 $in 查询创建一个字段值数组,您需要做一些额外的工作,例如:

    var friendIdsArr = [] //Initiate an array to store friend Ids
    db.friends.find({'userId':'jhdshh37838gsjj'},{'friendId':1,'_id':0}).forEach(function(x) {friendIdsArr.push(x.friendId);} ); //Foreach result in query, push value  to array.
    

    friendIdsArr 将是 [1,2]

    db.notes.find({'ownerId':'jhdshh37838gsjj', 'privateOrPublic':'public',{$in: ["friendId": friendIdsArr]}) 将给出结果,json 文档,匹配给定的条件。

    有趣的是,您的 notes 集合没有 note 字段。

    我建议您阅读 mongodb official documentation 并进行单个查询而不是两个不同的查询。

    【讨论】:

      猜你喜欢
      • 2012-03-21
      • 2014-07-28
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-30
      • 1970-01-01
      • 2017-11-22
      相关资源
      最近更新 更多