【问题标题】:How to limit MongoDB results with condition after the aggregation stage如何在聚合阶段之后使用条件限制 MongoDB 结果
【发布时间】:2021-11-04 08:11:28
【问题描述】:

我想在聚合阶段之后根据条件获取结果。我的代码给了我一个包含 4 个结果而不是 3 个的数组。 逻辑是用户滑动并将数据存储在一个集合中。集合存储第一次滑动,如果其他用户滑动现有条目,则更新集合文档而不是新插入,这取决于谁先滑动,因此 $or 查询。这工作正常,直到我在用户集合上将现有用户的连接状态更改为 false。结果是一个长度为 4 而不是 3 的数组。额外的数组是从 $or 查询创建的,并且只有 user_two。

滑动收藏 _id(ObjectID) - user_one(string) - user_two(string) - status_one(number) - status_two(number)

用户收藏 _id(ObjectID) - user_name(string) - hookups(boolean)

const fetchHookups = (req, res, next) => {
var query = {
        $or: [
             { user_one: ObjectId(req.body._id)},
             { user_two: ObjectId(req.body._id) },
            ]
        }
    
Swipe.aggregate([{
    $match: query
    },
    {
      $lookup: {
        from: 'users',
        let: { user_one: '$user_one', hookupstatus: true },
        pipeline: [{
        $match: {
        $expr: {
            $and: [
                { $eq: ["$_id", '$$user_one'] },
                { $eq: ["$hookups", '$$hookupstatus'] },
                ],
            }
        }
        }],
        as: "userone"
        }
    },
    {
      $unwind: {
        path: "$userone",
        preserveNullAndEmptyArrays: true,
        },
    },
    {
      $lookup: {
        from: 'users',
        let: { user_two: '$user_two', hookupstatus: true },
        pipeline: [{
        $match: {
        $expr: {
            $and: [
                { $eq: ["$_id", '$$user_two'] },
                { $eq: ["$hookups", '$$hookupstatus'] },
                ],
            }
        }
        }],
        as: "usertwo"
        }
    },
    {
      $unwind: {
        path: "$usertwo",
        preserveNullAndEmptyArrays: true,
        },
    },

    {
        $sort: {
            _id: -1
            }
        }
    ]).exec(function(error, response) {
        if (error) {
            console.log(error)
            } else {
                res.json(response)
                }
    })
}

【问题讨论】:

    标签: javascript node.js angular mongodb ionic-framework


    【解决方案1】:

    感谢@Thomas,我想通了,方法如下:

    {
     $redact: {
      $cond: [{
        $eq: ["$userone.hookups", true],
        $eq: ["$usertwo.hookups", true],
        },
        "$$KEEP",
        "$$PRUNE"
        ]
       }
    },
    

    【讨论】:

      【解决方案2】:

      我没有尝试过,但 $redact 运算符听起来就像你想要的那样。

      这是一个相当古老但写得很好的例子: Find documents whose array field contains at least n elements of a given array

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-21
        • 2019-01-06
        • 2021-03-20
        • 2020-01-18
        相关资源
        最近更新 更多