gpt4 book ai didi

javascript - 如何在 Mongoose 中只获得唯一值?

转载 作者:行者123 更新时间:2023-12-03 23:38:42 24 4
gpt4 key购买 nike

我只需要从集合中获取唯一值。例如:

const userID = `user1`;
const users = await Chat
.find({'$or': [{to: userID}, {from: userID}]})
.select(`-_id to from`)
.lean();

// users will be like:
[
{from: `user1`, to: `user2`},
{from: `user1`, to: `user2`},
{from: `user1`, to: `user2`},
{from: `user2`, to: `user1`},
{from: `user3`, to: `user1`},
// ... 10089 more items
];

// and I want this in result
const result = [`user2`, `user3`]; // exclude current user too
我知道我可以使用 JS 做到这一点。我可以从用户创建一个数组并运行 new Set() ,但它会很慢。 Mongoose 可以代替我这样做吗?

最佳答案

您可以尝试聚合查询,

  • $match您的情况
  • $group通过 null 并构造 from 的唯一数组用户和 to用户
  • $setUnion获得独一无二的users来自 fromto数组
  • $filter迭代上述联合数组的循环并删除当前用户
  • const userID = mongoose.Types.ObjectId(`user1`);
    const users = await Chat.aggregate([
    { $match: { $or: [{ to: userID }, { from: userID }] } },
    {
    $group: {
    _id: null,
    from: { $addToSet: "$from" },
    to: { $addToSet: "$to" }
    }
    },
    {
    $project: {
    _id: 0,
    users: {
    $filter: {
    input: { $setUnion: ["$from", "$to"] },
    cond: { $ne: ["$$this", userID] }
    }
    }
    }
    }
    ]).exec();

    console.log(users[0].users);
    Playground

    关于javascript - 如何在 Mongoose 中只获得唯一值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67449196/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com