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

如何在MongoDB中通过username字段查询获取对应的uuid值

MongoDB 通过指定username查询仅返回对应uuid的实现方案

你可以通过MongoDB的**投影(Projection)**功能实现需求,投影可以自定义查询返回的字段,自动过滤不需要的字段内容。

原生Mongo Shell写法

最基础的查询语句如下,替换对应的集合名和目标用户名即可:

# 替换your_collection为实际集合名,替换target_username为要查询的username值
db.your_collection.find(
  { username: "target_username" },
  { uuid: 1, _id: 0 }
)

如果需要直接提取uuid值,不需要返回文档结构,可以用findOne方法:

const targetUuid = db.your_collection.findOne(
  { username: "target_username" },
  { uuid: 1, _id: 0 }
)?.uuid;

常用驱动写法

  • Node.js Mongoose 场景
// 替换UserModel为你的集合对应的Mongoose模型
const userDoc = await UserModel.findOne(
  { username: "target_username" },
  { uuid: 1, _id: 0 }
).lean();
const targetUuid = userDoc?.uuid;
  • Python PyMongo 场景
# 替换collection为你的PyMongo集合实例
user_doc = collection.find_one(
  {"username": "target_username"},
  {"uuid": 1, "_id": 0}
)
target_uuid = user_doc.get("uuid") if user_doc else None

规则说明:投影配置中字段设为1代表仅返回该字段,设为0代表排除该字段。_id是MongoDB默认返回的字段,必须显式设为0才会隐藏;指定uuid:1后MongoDB会自动排除其他所有字段,包括不需要的username,无需额外显式排除。

内容的提问来源于stack exchange,提问作者J C

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 12:15:10