mongodb - $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 运算符的情况下运行查询,结果与以前相同。请指导我做错了什么或遗漏了什么?
谢谢!
解决方案
尝试这个 :
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}}}
推荐阅读
- php - 如何自定义我的 Laravel 电子邮件验证消息
- reactjs - React Table 未更新其值
- java - 导出到可运行 jar 后无法读取图像
- c - 两个结构初始化之间的区别
- azure-devops - 2+ Gb 工件的下载管道工件任务超过 100%
- java - Drools:比较 Drools 决策表中相同类型的对象
- rust - 转换选项
到一个选项 > - node.js - nodejs/npm - 使用 vpn 时包不工作
- php - 带有“反序列化”的刀片上的 Laravel 显示阵列
- ios - 是否可以验证已为已安装的 IOS 应用程序实例正确请求和配置了苹果应用程序站点关联文件?