投射一个并不总是存在的领域

Projecting a field that doesn't always exist

有没有办法投影可能存在或不存在的字段?例如定义为 null 或 undefined?

例如,我有一个查询:

$project: {
  date: 1,
  name: "$person.name",
  age: "$person.age"
}              

并非所有文档都保证有 $person.age,但不是将没有年龄的文档返回为 { date: Today, name: "Bill" },我希望它说 { date: Today, name: "Bill", age: null } 或类似的东西.

有没有比之后遍历数据并在字段不存在时创建字段更好的方法?

这里是 $ifNull expression comes into the fray. From the docs, $ifNull:

Evaluates an expression and returns the value of the expression if the expression evaluates to a non-null value. If the expression evaluates to a null value, including instances of undefined values or missing fields, returns the value of the replacement expression.

在您的情况下,以下将使用 $ifNull 表达式 return 非空 $person.age 字段值或字符串 "Unspecified" 如果年龄字段为空或不存在:

 $project: {
     date: 1,
     name: "$person.name",         
     age: { $ifNull: [ "$person.age", "Unspecified" ] }
 }    

使用$ifNull

  $project: {
     date: 1,
     name: "$person.name",
     age: { $ifNull: [ "$person.age", "null" ] }
  }  

您可以找到更多相关信息here

Mongo 5.3 开始,这是新 $fill 聚合运算符的一个很好的用例:

// { name: "Bill", age: 23 }
// { name: "Peter" }
db.collection.aggregate(
  { $fill: { output: { age: { value: "Unspecified" } } } }
)
// { name: "Bill",  age: 23 }
// { name: "Peter", age: "Unspecified" }

缺失值或设置为 null 的值用给定常量 fill 编辑 Unspecified


关于您的确切场景,您可以选择:

// { person: { name: "Bill", age: 23 } }
// { person: { name: "Peter" } }
db.collection.aggregate([
  { $project: { name: "$person.name" , age: "$person.age" } },
  { $fill: { output: { "age": { value: "Unspecified" } } } }
])
// { name: "Bill",  age: 23 }
// { name: "Peter", age: "Unspecified" }