【问题标题】:MongoDB find documents with a field not empty, IF EXISTSMongoDB查找字段不为空的文档,如果存在
【发布时间】:2022-01-09 21:50:49
【问题描述】:

如果该字段存在,我希望能够查询具有特定字段值不为空的文档。通常我会这样做:

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" : "",
}

【问题讨论】:

  • 试试.find({ client_comment: { $exists: true, $eq: {$size: 0} } })
  • 不返回任何记录

标签: mongodb typeorm robo3t


【解决方案1】:

查询1

  • 寻找解决方案
  • 如果字段为missing 或其非空字符串,则保留文档

Test code here

db.collection.find({
  $or: [
    {client_comment: {$exists: false}},
    {client_comment: {$ne: ""}}
  ]
})

查询2

  • 聚合解决方案
  • 如果字段为 missing 或其非空字符串,则保留文档

Test code here

aggregate(
[{"$match": 
    {"$expr": 
      {"$or": 
        [{"$eq": [{"$type": "$client_comment"}, "missing"]},
         {"$ne": ["$client_comment", ""]}]}}}])

【讨论】:

    猜你喜欢
    • 2012-01-23
    • 2021-12-02
    • 2017-05-15
    • 1970-01-01
    • 2021-04-24
    • 1970-01-01
    • 2014-04-12
    • 2013-04-16
    • 2020-08-09
    相关资源
    最近更新 更多