【问题标题】:How to compare fields inside an embedded array with the field at root level?如何将嵌入数组中的字段与根级别的字段进行比较?
【发布时间】:2019-09-13 20:20:25
【问题描述】:

我有一个包含 2 个集合的 MongoDB,我正在努力解决如何执行涉及这 2 个集合的复杂查询。

我的环境是nodejs和mongoose。

我看到也许 aggregate 可以使用,但我不确定。

我的收藏:

1) 用户集合

{
    "_id":{"$oid":"xxxxxxx"},
    …
}

2) 聊天收藏

{
    "_id": {
        "$oid": "aaaaaaa"
    },
    "participants": [
        {
            "user": {
                "$oid": "xxxxxxxxx"
            },
            "lastRead": {
                "$date": {
                    "$numberLong": "1562673141916"
                }
            }
        }, {
            "user": {
                "$oid": "zzzzzzzzz"
            },
            "lastRead": {
                "$date": {
                    "$numberLong": "1562683663751"
                }
            }
        }
    ],
    "lastMessageAt": {
        "$date": {
            "$numberLong": "1562673141867"
        }
    }
}

如何查询聊天集合以检索,而不是聊天,而是具有未读消息的用户(如果可能,唯一)(participant.lastRead

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    以下查询可以得到我们预期的输出:

    db.chat.aggregate([
        {
            $unwind:"$participants"
        },
        {
            $match:{
                $expr:{
                    $lt:["$participants.lastRead","$lastMessageAt"]
                }
            }
        },
        {
            $group:{
                "_id":null,
                "users":{
                    $addToSet:"$participants.user"
                }
            }
        },
        {
            $project:{
                "_id":0
            }
        }
    ]).pretty()
    

    【讨论】:

    • 非常感谢它运行良好!我有最后一个问题:我的聊天模型没有嵌入用户,我在需要时使用人口。如何在此处使用此查询添加人口,我需要检索完整用户。
    • @PhoenK 可以直接将$lookupusers 数组放入User 集合中。请查看docs.mongodb.com/manual/reference/operator/aggregation/lookup。如果您遇到任何问题,请告诉我。
    • 谢谢,昨天正在尝试,并得到您的确认!
    猜你喜欢
    • 1970-01-01
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 2017-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多