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

MongoServerError报错求助:投影中无法对date字段做排除操作

MongoDB报错:MongoServerError: Cannot do exclusion on field date in inclusion projection

报错原因

MongoDB的投影规则明确:不能在同一条查询中同时混合使用包含型投影(字段设为1)和排除型投影(字段设为0),唯一例外是_id字段(可以在包含其他字段时单独排除_id:0)。你执行的查询db.posts.find({}, {title: 1, date: 0})同时指定了包含title、排除date,直接违反了这个规则,因此触发报错。

解决方法

根据你的需求,分两种方案选择:

方案1:仅保留title和默认的_id字段

如果只需要获取title字段(MongoDB默认会返回_id),直接使用包含型投影即可,自动排除其他字段(包括date):

db.posts.find({}, {title: 1})

返回结果示例:

[
  { _id: ObjectId("63739044de169f6d0h2e6a3d"), title: 'Post 2' },
  { _id: ObjectId("63739271de179f5d0e31e5b2"), title: 'Post 1' }
]

方案2:保留除date外的所有字段

如果需要保留title以及其他所有字段,仅排除date,使用排除型投影:

db.posts.find({}, {date: 0})

返回结果示例:

[
  {
    _id: ObjectId("63739044de169f6d0h2e6a3d"),
    title: 'Post 2',
    body: 'a news post',
    category: 'News',
    likes: 1,
    tags: [ 'news', 'events' ]
  },
  {
    _id: ObjectId("63739271de179f5d0e31e5b2"),
    title: 'Post 1',
    body: 'hey there, hemant here',
    category: 'random',
    likes: 1,
    tags: [ 'random', 'events' ]
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 17:30:12