首页 > 解决方案 > $exists 不适用于 MongoDb 聚合中的 $match 阶段

问题描述

我正在开发 Mongodb v3.6。我正在尝试运行有关客户评论的查询。在这个查询中,我只需要那些具有“review”字段值的文档。为此,我执行了以下查询:

db.customer_reviews.aggregate([
{$match: {rating: { $gte: 3}, review: {$ne: "", $exists: true}}},
{$lookup: {
"localField": "uid",
"from": "users",
"foreignField": "_id",
"as": "review_fields"
}},
{"$unwind": "$review_fields"},
]).pretty()

我有一些不包含评论字段或值为空字符串的文档,例如:

{
        "_id" : 1,
        "uid" : 8,
        "booking_id" : 1,
        "rating" : 4.5,
        "review" : "This is very fast.",
        "rated_by" : 1,
        "dont_send_notification" : false
}
{
        "_id" : 2,
        "uid" : 8,
        "booking_id" : 1,
        "rating" : 5,
        "review" : "",
        "rated_by" : 1,
        "dont_send_notification" : false
}
{
        "_id" : 3,
        "uid" : 8,
        "booking_id" : 17,
        "rating" : 5,
        "review" : "This team work's very fast and well. And I really appriciated there work and hard work. I really like this software.",
        "rated_by" : 1,
        "dont_send_notification" : false
}
{
        "_id" : 7,
        "uid" : 8,
        "booking_id" : 21,
        "rating" : 5,
        "rated_by" : 1,
        "dont_send_notification" : false
}
{
        "_id" : 8,
        "uid" : 8,
        "booking_id" : 21,
        "rating" : 5,
        "rated_by" : 1,
        "dont_send_notification" : false
}

但是在这个查询中,我仍然得到不包含评论字段或具有空白值的文档。我已经阅读了 $exists 运算符的文档。

https://docs.mongodb.com/v3.6/reference/operator/query/exists/

我还尝试在没有 $ne 运算符的情况下运行查询,结果与以前相同。请指导我做错了什么或遗漏了什么?

谢谢!

标签: mongodb

解决方案


尝试这个 :

db.customer_reviews.aggregate([
{$match: {rating: { $gte: 3}, review: {$exists: true, $nin: [ "", null ]}}},
{$lookup: {
"localField": "uid",
"from": "users",
"foreignField": "_id",
"as": "review_fields"
}},
{"$unwind": "$review_fields"},
]).pretty()

理想情况下,您应该在写入您的customer_reviews. review只有当某些用户给出了有效的评论时,该字段才应该存在。这样你所要做的就是 {$match: {rating: { $gte: 3}, review: {$exists: true}}}


推荐阅读