MongoDB如何查询testimony字段非空的最新3条用户记录?
解决MERN栈中查询含非空testimony字段的最新用户问题
问题背景
开发基督教社交媒体应用,基于MERN栈,User模型包含嵌套的details对象,其中testimony字段存储用户信仰见证。用户注册时details对象不存在,添加见证后才创建。需要查询**testimony非空的最新三位用户**。
User模型的details定义:
details: { testimony: { type: String, }, bio: { type: String, }, }
现有方案的问题
- 第一个查询使用
details: { testimony: { $exists: false } },逻辑完全相反(查找无testimony的用户),且嵌套字段查询写法错误,MongoDB嵌套字段需用点符号访问 - 第二、第三个查询直接写
testimony,未指定details.前缀,无法定位到嵌套字段 - 排序用
createdAt: 1是升序(最早用户在前),要获取最新用户需用降序createdAt: -1 - 第三个查询中
$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
相关产品推荐
相关产品推荐

