新聞中心
AggregateCommand.cond(value: any): Object
支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web
創(chuàng)新互聯(lián)堅持“要么做到,要么別承諾”的工作理念,服務(wù)領(lǐng)域包括:成都網(wǎng)站設(shè)計、成都做網(wǎng)站、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣等服務(wù),滿足客戶于互聯(lián)網(wǎng)時代的旅順口網(wǎng)站設(shè)計、移動媒體設(shè)計的需求,幫助企業(yè)找到有效的互聯(lián)網(wǎng)解決方案。努力成為您成熟可靠的網(wǎng)絡(luò)建設(shè)合作伙伴!
聚合操作符。計算布爾表達式,返回指定的兩個值其中之一。
參數(shù)
value: any
返回值
Object
API 說明
cond 的使用形式如下:
cond({ if: <布爾表達式>, then: <真值>, else: <假值> })
或者:
cond([ <布爾表達式>, <真值>, <假值> ])
兩種形式中,三個參數(shù)(if、then、else)都是必須的。
如果布爾表達式為真,那么 $cond 將會返回 <真值>,否則會返回 <假值>
示例代碼
假設(shè)集合 items 的記錄如下:
{ "_id": "0", "name": "item-a", "amount": 100 }
{ "_id": "1", "name": "item-b", "amount": 200 }
{ "_id": "2", "name": "item-c", "amount": 300 }
我們可以使用 cond,根據(jù) amount 字段,來生成新的字段 discount:
const $ = db.command.aggregate
db.collection('items').aggregate()
.project({
name: 1,
discount: $.cond({
if: $.gte(['$amount', 200]),
then: 0.7,
else: 0.9
})
})
.end()
輸出如下:
{ "_id": "0", "name": "item-a", "discount": 0.9 }
{ "_id": "1", "name": "item-b", "discount": 0.7 }
{ "_id": "2", "name": "item-c", "discount": 0.7 }AggregateCommand.ifNull(value: Expression[]): Object
支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web
聚合操作符。計算給定的表達式,如果表達式結(jié)果為 null、undefined 或者不存在,那么返回一個替代值;否則返回原值。
參數(shù)
value: Expression[]
[ <表達式>, <替代值> ]
返回值
Object
API 說明
ifNull 的使用形式如下:
ifNull([ <表達式>, <替代值> ])
示例代碼
假設(shè)集合 items 的記錄如下:
{ "_id": "0", "name": "A", "description": "這是商品A" }
{ "_id": "1", "name": "B", "description": null }
{ "_id": "2", "name": "C" }
我們可以使用 ifNull,對不存在 desc 字段的文檔,或者 desc 字段為 null 的文檔,補充一個替代值。
const $ = db.command.aggregate
db.collection('items').aggregate()
.project({
_id: 0,
name: 1,
description: $.ifNull(['$description', '商品描述空缺'])
})
.end()
輸出如下:
{ "name": "A", "description": "這是商品A" }
{ "name": "B", "description": "商品描述空缺" }
{ "name": "C", "description": "商品描述空缺" }AggregateCommand.switch(value: any): Object
支持端:小程序 2.7.4, 云函數(shù) 0.8.1, Web
聚合操作符。根據(jù)給定的 switch-case-default 計算返回值、
參數(shù)
value: any
返回值
Object
API 說明
switch 的使用形式如下:
switch({
branches: [
case: <表達式>, then: <表達式>,
case: <表達式>, then: <表達式>,
...
],
default: <表達式>
})
示例代碼
假設(shè)集合 items 的記錄如下:
{ "_id": "0", "name": "item-a", "amount": 100 }
{ "_id": "1", "name": "item-b", "amount": 200 }
{ "_id": "2", "name": "item-c", "amount": 300 }
我們可以使用 switch,根據(jù) amount 字段,來生成新的字段 discount:
const $ = db.command.aggregate
db.collection('items').aggregate()
.project({
name: 1,
discount: $.switch({
branches: [
{ case: $.gt(['$amount', 250]), then: 0.8 },
{ case: $.gt(['$amount', 150]), then: 0.9 }
],
default: 1
})
})
.end()
輸出如下:
{ "_id": "0", "name": "item-a", "discount": 1 }
{ "_id": "1", "name": "item-b", "discount": 0.9 }
{ "_id": "2", "name": "item-c", "discount": 0.8 } 網(wǎng)站欄目:創(chuàng)新互聯(lián)小程序教程:SDK數(shù)據(jù)庫Command·聚合操作符·條件操作符
分享URL:http://www.dlmjj.cn/article/dhpdhsi.html


咨詢
建站咨詢

