You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB如何查询testimony字段非空的最新3条用户记录?

解决MERN栈中查询含非空testimony字段的最新用户问题

问题背景

开发基督教社交媒体应用,基于MERN栈,User模型包含嵌套的details对象,其中testimony字段存储用户信仰见证。用户注册时details对象不存在,添加见证后才创建。需要查询**testimony非空的最新三位用户**。

User模型的details定义:

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

现有方案的问题

  1. 第一个查询使用details: { testimony: { $exists: false } },逻辑完全相反(查找无testimony的用户),且嵌套字段查询写法错误,MongoDB嵌套字段需用点符号访问
  2. 第二、第三个查询直接写testimony,未指定details.前缀,无法定位到嵌套字段
  3. 排序用createdAt: 1是升序(最早用户在前),要获取最新用户需用降序createdAt: -1
  4. 第三个查询中$ne: []错误,testimony是字符串类型,空值应为""而非空数组

正确查询语句

const latestTestimonies = await User.find({
  // 确保details对象存在
  details: { $exists: true },
  // 确保testimony存在且不为空字符串
  "details.testimony": { $exists: true, $ne: "" }
})
.sort({ createdAt: -1 }) // 降序排列,最新用户在前
.limit(3)
.select('-password');

补充说明

如果需要过滤掉仅含空格的testimony,可结合$trim操作(MongoDB 4.0+支持):

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

内容的提问来源于stack exchange,提问作者Stephen Scott Moore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 12:52:25