【问题标题】:Retrieve all documents where _ids are in another collection检索 _ids 在另一个集合中的所有文档
【发布时间】:2016-05-27 07:59:22
【问题描述】:

我想返回“usersessions”集合中_ids 在我的“users”集合中的所有文档。

我尝试了以下方法:

db.usersessions.find( { "userId": { $in: (db.getCollection('users').find({},{"_id":1})) }  } )

返回错误:

错误:error: { "waitedMS" : NumberLong(0), "ok" : 0, "errmsg" : "$in 需要一个数组", "code" : 2 }

【问题讨论】:

    标签: mongodb mongodb-query


    【解决方案1】:

    如错误消息$in 中所述,需要一个数组。您可以使用distinct 从“用户”集合中返回一个_id 数组。原因是 _id 在集合中是唯一的。

    var ids = db.getCollection('users').distinct('_id');
    db.usersessions.find( { "userId": { "$in": ids } })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-29
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多