database - 在数组中查找 ObjectId

标签 database mongodb mongodb-query aggregation-framework

我有商店集合和用户集合,其中包含商店 ID 列表作为字符串。

商店文件示例:

    {
            "_id" : ObjectId("5a0c6797fd3eb67969316ce2"),
            "picture" : "http://placehold.it/150x150",
            "name" : "Genmom",
            "email" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4f232a26232e382e3d2a0f282a21222022612c2022" rel="noreferrer noopener nofollow">[email protected]</a>",
            "city" : "Rabat",
            "location" : {
                    "type" : "Point",
                    "coordinates" : [
                            -6.79387,
                            33.83957
                    ]
            }
    }

用户收集示例:

{
            "_id" : ObjectId("5c04b943ff491824b806686a"),
            "email" : "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="13726a7c66713d787b7a727f53747e727a7f3d707c7e" rel="noreferrer noopener nofollow">[email protected]</a>",
            "password" : "$2a$10$4Wt5Rn6udxREdXCIt3hGb.sKhKUKOlyiYKmLTjYG3SqEPKFSw9phq",
            "likedShops" : [
                    "5a0c6797fd3eb67969316ce2",
                    "5c07ada8ff49183284e509d1",
                    "5c07acc1ff49183284e509d0"
            ],
            "dislikedShops" : [ ]
}

我想返回 LikeShops 的详细信息。

最佳答案

您可以使用下面的 $lookup聚合

db.users.aggregate([
  { "$lookup": {
    "from": "shops",
    "let": { "likedShops": "$likedShops" },
    "pipeline": [
      { "$match": { "$expr": { "$in": ["$_id", "$$likedShops"] }}}
    ],
    "as": "likedShops"
  }}
])

或者,如果您的 ID 是字符串,则使用 $toStringObjectIds

的聚合
db.users.aggregate([
  { "$lookup": {
    "from": "shops",
    "let": { "likedShops": "$likedShops" },
    "pipeline": [
      { "$match": { "$expr": { "$in": [{ "$toString": "$_id" }, "$$likedShops"] }}}
    ],
    "as": "likedShops"
  }}
])

关于database - 在数组中查找 ObjectId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53636832/

相关文章:

mongodb - MongoDB observeOn 为什么不使用指定的执行上下文?

javascript - MongoClient 类型错误

Mongodb $geoIntersect 问题

php - CodeIgniter - 如何将表单中的值发布为 NULL 而不是 0

database - 我应该检查代码中的数据库约束还是应该捕获数据库抛出的异常

MySQL 两张表带键的设计

php - 验证数据库中是否存在输入的用于请求密码的电子邮件

node.js - 查询已完成的级别

Mongodb $cond 与 find

MongoDB:如何在嵌套数组中插入对象?