获取MongoDB中字段不为null或空的最后N条记录的方法:

huangapple go评论61阅读模式
英文:

How to get the last N records where a field is not null or empty in MongoDB

问题

我正在开发一个MERN基督教社交媒体应用程序,允许用户分享关于他们信仰的见证。用户模型具有一个包含见证、简介等信息的details对象。我尝试查询数据库,以显示最近的三个用户,其中见证字段不为空。当用户注册时,details对象不存在,但当他们添加见证时,它会在数据库中创建。

用户模型中的details对象如下所示:

details: {
  testimony: {
    type: String,
  },
  bio: {
    type: String,
  },
}

我找到了一些可能的解决方案,但无法使它们工作:

const testimony = await User.find({
  details: { testimony: { $exists: false } },
})
  .sort({ createdAt: 1 })
  .limit(3)
  .select('-password');

我尝试过去掉details:

const testimony = await User.find({
  testimony: { $exists: true } ,
})
  .sort({ createdAt: 1 })
  .limit(3)
  .select('-password');

对于上面的最后一个尝试,如果我将$exits: false更改为$exits: true,它将显示具有或不具有见证字段的最后三条记录。

我尝试了其他一些在其他问题中找到的建议,但无法使任何方法都起作用。另一个我尝试的是:

const testimony = await User.find({
  testimony: { $exists: true, $ne: [] },
})
  .sort({ createdAt: 1 })
  .limit(3)
  .select('-password');
英文:

I'm working on a MERN christian social media app that will allow user to share a testimony about their faith. The User modal has a details object with tesitmony, bio, etc. I am trying to query the database to show the last three users where the testimony field is not empty. When the user registers the details object does not exist but when they add a testimony it is created in the db.
The details object in the User modal looks like:

details: {
  testimony: {
    type: String,
  },
  bio: {
    type: String,
  },
}

I found some possible solutions but cann't get them to work:

const testimony = await User.find({
      details: { testimony: { $exists: false } },
    })
      .sort({ createdAt: 1 })
      .limit(3)
      .select('-password');

I've tried it without the details:

const testimony = await User.find({
      testimony: { $exists: true } ,
    })
      .sort({ createdAt: 1 })
      .limit(3)
      .select('-password');

With this last one above, if I change $exits: false it will show the last three records with or without the testimony field.

I've tried several other suggestions I fouund in other questions but I cannot get anything to work. Anoter one I tried is:

const testimony = await User.find({
      testimony: { $exists: true, $ne: [] },
    })
      .sort({ createdAt: 1 })
      .limit(3)
      .select('-password');

答案1

得分: 2

这个选项怎么样:

db.x.find({
    "details.testimony": { 
        $nin: [ 
            null,
            ""
        ]
    }
}).sort({ 
    createdAt: -1
}).limit(2)

其中:

只匹配不为null且不为空的testimony,根据createdAt字段降序排序,并且限制输出记录数量为n=2。

(注意:当字段不存在时,这等同于字段为null。)

英文:

How about this option:

 db.x.find({
          "details.testimony":{ 
                  $nin:[ 
                        null,
                        "" 
                        ]
                    }
            }).sort( 
                    { 
                     createdAt:-1
                    }
                   ).limit(2)

where:

You match only testimony not null and not empty , you sort based on createdAt filed in DESCENDING order and you limit the number of records in the output to n=2

( note when field do not exist this is equivalent to when the field is null )

答案2

得分: 0

$exists: true参数只过滤文档中存在该字段/对象的地方,不考虑其值。因此,除了使用$exists: true之外,还可以使用$ne(不等于)参数,如$ne: '',用于文档中该字段为空的情况,以及$type: 'string',以排除具有null值的情况。

更新您的查询如下:

User.find({
  'details.testimony': { $exists: true, $ne: '', $type: 'string' }
})

或者

使用nin: ['', null](不在其中)来排除所有具有空字段或null的文档。

更新您的查询如下:

User.find({
  'details.testimony': { $exists: true, $nin: ['', null] }
})

希望对您有所帮助。

英文:

The $exists: true parameter just filters wherever the that field/object is present in the document irrespective of the value. So, along with $exists: true use $ne (not equals) parameter as $ne: '' to documents where its empty, and $type: 'string' to omit the ones with null.

Update your query as:

User.find({
  'details.testimony': { $exists: true, $ne: '', $type: 'string' }
})

OR

Use nin: ['', null] (not in) to omit all documents with empty field or null.

Update your query as:

User.find({
  'details.testimony': { $exists: true, $nin: ['', null] }
})

Hope this helps

huangapple
  • 本文由 发表于 2023年6月30日 01:20:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76583298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定