如何检查文档中是否存在某个元素,并根据该元素返回true或false?

时间:2019-06-16 13:40:43

标签: mongodb mongoose mongodb-query aggregation-framework

我有一个聚合查询,其中使用$lookup从其他集合中获取数据。但是我不明白,如果找到$match,如何获得布尔值。

架构

const likesSchema    = new mongoose.Schema({
user: {
    id: {
        type: String,
        required: true,
    },
    name: {
        type: String,
        required: true,
    },
},
storyID: {
    type: String,
    required: true,
}
}, {
    timestamps: true
});

完整查询

const user_id         = req.authorizedUser.sub;

const stories = await Story.aggregate([
                {
                    $lookup: {
                        from: "comments",
                        localField: "storyID",
                        foreignField: "storyID",
                        as: "comments"
                    },
                },

                {
                    $lookup: {
                        from: "likes",
                        let: {storyID: "$storyID"},
                        pipeline: [
                            {
                                $match: {
                                    $expr: { $eq: ["$$storyID", "$storyID"] }
                                }
                            },
                            {
                                $facet: {
                                    "total": [{ $count: "count" }],
                                    "byMe": [{
                                        $match: {
                                            $expr: { $eq: ["$user.id", user_id] } // Need boolean value if found/ not found
                                        }
                                    }]
                                }
                            }
                        ],
                        as: "likes"
                    }
                },

响应摘录

"likes": [
                {
                    "total": [
                        {
                            "count": 2
                        }
                    ],
                    "byMe": [
                        {
                            "_id": "5d04fe8e982bb50bbcbd2b48",
                            "user": {
                                "id": "63p6PpPyOh",
                                "name": "Ayan Dey"
                            },
                            "storyID": "b0g5GA6ZJFKkJcnJlp6w8qGR",
                            "createdAt": "2019-06-15T14:19:58.531Z",
                            "updatedAt": "2019-06-15T14:19:58.531Z",
                            "__v": 0
                        }
                    ]
                }
            ]

必需的响应

"likes": {
    "total": 2,
    "byMe": true
}

1 个答案:

答案 0 :(得分:2)

您可以使用以下汇总

(?:\d+[a-z]|[a-z]+\d)[a-z\d]*

pattern 1|pattern 2