MongoDB 查找字段不为空的文档,如果存在
MongoDB find documents with a field not empty, IF EXISTS
我希望能够查询特定字段值不为空的文档(如果该字段存在)。通常我会做类似的事情:
client_comment: { '$exists': true, '$ne': null },
'$expr': { '$eq': [ { "$ne": "$client_comment" }, null ] },
事实是,有些记录有这个字段,有些没有...还有一些是空字符串。我想排除那些具有 client_comment
值的空字符串,但我不知道该怎么做。
{
"_id" : ObjectId("5e0b1b094dfee4f3a2f4f62a"),
"name" : "Jane Doe",
"email" : "john_doe@gmail.com",
"status" : "done",
"created_date" : ISODate("2021-10-03T19:38:56.462Z"),
"updated_date" : ISODate("2021-10-03T19:38:56.462Z"),
}
{
"_id" : ObjectId("5e0b1b094dcee4f3a2f4f62a"),
"name" : "Lorem Ipsum",
"email" : "test@gmail.com",
"status" : "done",
"created_date" : ISODate("2021-10-03T19:38:56.462Z"),
"updated_date" : ISODate("2021-10-03T19:38:56.462Z"),
"client_comment" : "Lorem ipsum",
}
// Exclude this record from the result
{
"_id" : ObjectId("5e0b1b094dfef4f3a2f4f62a"),
"name" : "John Doe",
"email" : "jane.doe@gmail.com",
"status" : "done",
"created_date" : ISODate("2021-10-03T19:38:56.462Z"),
"updated_date" : ISODate("2021-10-03T19:38:56.462Z"),
"client_comment" : "",
}
查询 1
- 寻找解决方案
- 如果字段为
missing
或其非空字符串则保留文档
find({"$or":
[{"client_comment": {"$exists": false}}, {"client_comment": {"$ne": ""}}]})
查询2
- 综合解决方案
- 如果字段为
missing
或其非空字符串则保留文档
aggregate(
[{"$match":
{"$expr":
{"$or":
[{"$eq": [{"$type": "$client_comment"}, "missing"]},
{"$ne": ["$client_comment", ""]}]}}}])
我希望能够查询特定字段值不为空的文档(如果该字段存在)。通常我会做类似的事情:
client_comment: { '$exists': true, '$ne': null },
'$expr': { '$eq': [ { "$ne": "$client_comment" }, null ] },
事实是,有些记录有这个字段,有些没有...还有一些是空字符串。我想排除那些具有 client_comment
值的空字符串,但我不知道该怎么做。
{
"_id" : ObjectId("5e0b1b094dfee4f3a2f4f62a"),
"name" : "Jane Doe",
"email" : "john_doe@gmail.com",
"status" : "done",
"created_date" : ISODate("2021-10-03T19:38:56.462Z"),
"updated_date" : ISODate("2021-10-03T19:38:56.462Z"),
}
{
"_id" : ObjectId("5e0b1b094dcee4f3a2f4f62a"),
"name" : "Lorem Ipsum",
"email" : "test@gmail.com",
"status" : "done",
"created_date" : ISODate("2021-10-03T19:38:56.462Z"),
"updated_date" : ISODate("2021-10-03T19:38:56.462Z"),
"client_comment" : "Lorem ipsum",
}
// Exclude this record from the result
{
"_id" : ObjectId("5e0b1b094dfef4f3a2f4f62a"),
"name" : "John Doe",
"email" : "jane.doe@gmail.com",
"status" : "done",
"created_date" : ISODate("2021-10-03T19:38:56.462Z"),
"updated_date" : ISODate("2021-10-03T19:38:56.462Z"),
"client_comment" : "",
}
查询 1
- 寻找解决方案
- 如果字段为
missing
或其非空字符串则保留文档
find({"$or":
[{"client_comment": {"$exists": false}}, {"client_comment": {"$ne": ""}}]})
查询2
- 综合解决方案
- 如果字段为
missing
或其非空字符串则保留文档
aggregate(
[{"$match":
{"$expr":
{"$or":
[{"$eq": [{"$type": "$client_comment"}, "missing"]},
{"$ne": ["$client_comment", ""]}]}}}])