MongoDB聚合查找删除数组

发布于 2025-01-12 21:17:15 字数 1005 浏览 0 评论 0原文

我目前正在使用 mongoose 的聚合查找方法,它的工作原理是:

const data = await this.messageModel.aggregate([
    {
        $match: { channel_id: channel_id },
    },
    {
        $limit: limit ? limit : 1000,
    },
]).lookup({
    from: 'users',
    localField: 'author',
    foreignField: 'id',
    as: 'author',
    pipeline: [
        { $project: { _id: 0, password: 0, email: 0, __v: 0 } }
    ],
});

数据返回一个像这样的对象数组

{
        "_id": "622861fe264eaed05a32bb2d",
        "channel_id": "5850473746686541647",
        "author": [
            {
                "username": "UnusualAbsurd",
                "status": "Working...",
                "createdAt": "2022-03-08T14:02:53.728Z",
                "id": "1"
            }
        ],
        "id": "5850638795510120271",
        "createdAt": "2022-03-09T08:14:54.228Z",
        "attachments": [],
        "content": "zazaza",
        "__v": 0
}

现在的问题是,我使用 lookup() 方法返回的作者对象作为大批。如何让它不以数组形式返回?

I am currently using an aggregate lookup method from mongoose and it works:

const data = await this.messageModel.aggregate([
    {
        $match: { channel_id: channel_id },
    },
    {
        $limit: limit ? limit : 1000,
    },
]).lookup({
    from: 'users',
    localField: 'author',
    foreignField: 'id',
    as: 'author',
    pipeline: [
        { $project: { _id: 0, password: 0, email: 0, __v: 0 } }
    ],
});

The data returns an array of object like this

{
        "_id": "622861fe264eaed05a32bb2d",
        "channel_id": "5850473746686541647",
        "author": [
            {
                "username": "UnusualAbsurd",
                "status": "Working...",
                "createdAt": "2022-03-08T14:02:53.728Z",
                "id": "1"
            }
        ],
        "id": "5850638795510120271",
        "createdAt": "2022-03-09T08:14:54.228Z",
        "attachments": [],
        "content": "zazaza",
        "__v": 0
}

Now the problem is, the author object that I used the lookup() method on returns as an array. How do I make it not return as an array?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

メ斷腸人バ 2025-01-19 21:17:15

您可以在查找后使用 $unwind ,如下所示:

{$unwind: '$author'}

You can use $unwind after lookup like this:

{$unwind: '$author'}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文