MongoDB聚合中正确判断book_subscription是否为null并设置book_count
MongoDB聚合:根据book_subscription是否为null设置book_count
集合数据
[ { _id: ObjectId("637d05dc32428ed75ea08d09"), book_details: { book_subscription: null, book_auth: 'Amber' }, book_name: 'random123' }, { _id: ObjectId("637d0673ce0f17f6c473dee2"), book_details: { book_subscription: ObjectId('637d06a545a17f0e686ecf3a'), book_auth: 'Shurya' }, book_name: 'random321' }, { _id: ObjectId("637d069a3d597c8458ebe4ec"), book_details: { book_subscription: ObjectId('637d06ac82f0760b03fdea0d'), book_auth: 'Aman' }, book_name: 'random676' }, { _id: ObjectId("637d06c05b32d503007bcb54"), book_details: { book_subscription: null, book_auth: 'Saurav' }, book_name: 'random999' } ]
需求
当book_details.book_subscription不为null时,新增字段book_count为1;当该字段为null时,book_count为0。
错误尝试
以下语句执行后,即使book_subscription为null,book_count仍会被设为1:
db.bookSchema.aggregate([ { "$addFields": { "book_count": { "$cond": { "if": { "$ne": [ "book_details.book_subscription", null ] }, "then": 1, "else": 0 } } } } ])
错误原因
代码中直接使用字符串"book_details.book_subscription"进行比较,MongoDB会将其视为普通字符串而非字段引用。由于字符串永远不等于null,所以所有文档的book_count都会被设为1。
正确解法
需要用$前缀引用字段,告诉MongoDB要读取文档中的对应字段值进行比较。以下是几种常用的正确写法:
写法一:完整$cond语法
db.bookSchema.aggregate([ { "$addFields": { "book_count": { "$cond": { "if": { "$ne": ["$book_details.book_subscription", null] }, "then": 1, "else": 0 } } } } ])
写法二:$cond简写形式
db.bookSchema.aggregate([ { "$addFields": { "book_count": { "$cond": [ { "$ne": ["$book_details.book_subscription", null] }, 1, 0 ] } } } ])
写法三:$ifNull简化逻辑
利用$ifNull判断字段是否为null,结合$cond返回对应值:
db.bookSchema.aggregate([ { "$addFields": { "book_count": { "$cond": [{ "$ifNull": ["$book_details.book_subscription", false] }, 1, 0] } } } ])
内容的提问来源于stack exchange,提问作者Sushant Rad
相关产品推荐
相关产品推荐

