$default

语法

  1. { <字段名1>: { $default: <默认值1> }, <字段名2>: { $default: <默认值2>, ... } }

描述

选择某个字段。当字段不存在时返回默认值,可简写为:

  1. { <字段名1>: <默认值1>, <字段名2>: <默认值2>, ... }

示例

在集合 sample.employee 插入1条记录:

  1. > db.sample.employee.insert( { "_id": 1, "class": 1, "students": [ { "name": "ZhangSan", "age": 18 }, { "name": "LiSi", "age": 19 },{ "name": "WangErmazi", "age": 18 } ] } )

SequoiaDB shell 运行如下:

  • 查询集合 sample.employee 的记录,指定返回字段“students”和“teacher”,并且设置默认值:

    1. > db.sample.employee.find( {}, { "students": [], "teacher": { "$default": "Mr Liu" } } )
    2. {
    3. "students": [
    4. {
    5. "name": "ZhangSan",
    6. "age": 18
    7. },
    8. {
    9. "name": "LiSi",
    10. "age": 19
    11. },
    12. {
    13. "name": "WangErmazi",
    14. "age": 18
    15. }
    16. ],
    17. "teacher": "Mr Liu"
    18. }
    19. Return 1 row(s).