$ exists不适用于MongoDb聚合中的$ match阶段

时间:2019-03-04 12:30:56

标签: mongodb

我正在使用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运算符的情况下运行查询,其结果与之前相同。请指导我在做什么错或缺少什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试一下:

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}}}