SDK數(shù)據(jù)庫 Command·查詢·數(shù)組操作符

2022-05-12 16:54 更新

Command.all(values: any[]): Command

支持端:小程序 2.8.3, 云函數(shù) 1.2.1, Web

數(shù)組查詢操作符。用于數(shù)組字段的查詢篩選條件,要求數(shù)組字段中包含給定數(shù)組的所有元素。

參數(shù)

values: any[]

返回值

Command

示例代碼 1:普通數(shù)組

找出 tags 數(shù)組字段同時包含 cloud 和 database 的記錄

const _ = db.command
db.collection('todos').where({
  tags: _.all(['cloud', 'database'])
})
.get({
  success: console.log,
  fail: console.error
})

示例代碼 2:對象數(shù)組

如果數(shù)組元素是對象,則可以用 _.elemMatch 匹配對象的部分字段

假設(shè)有字段 places 定義如下:

{
  "type": string
  "area": number
  "age": number
}

找出數(shù)組字段中至少同時包含一個滿足 “area 大于 100 且 age 小于 2” 的元素和一個滿足 “type 為 mall 且 age 大于 5” 的元素

const _ = db.command
db.collection('todos').where({
  places: _.all([
    _.elemMatch({
      area: _.gt(100),
      age: _.lt(2),
    }),
    _.elemMatch({
      name: 'mall',
      age: _.gt(5),
    }),
  ]),
})
.get({
  success: console.log,
  fail: console.error,
})




Command.elemMatch(condition: Object|Command): Command

支持端:小程序 2.8.3, 云函數(shù) 1.2.1, Web

用于數(shù)組字段的查詢篩選條件,要求數(shù)組中包含至少一個滿足 elemMatch 給定的所有條件的元素

參數(shù)

condition: Object|Command

匹配條件

返回值

Command

示例代碼:數(shù)組是對象數(shù)組的情況

假設(shè)集合示例數(shù)據(jù)如下:

{
  "_id": "a0",
  "city": "x0",
  "places": [{
    "type": "garden",
    "area": 300,
    "age": 1
  }, {
    "type": "theatre",
    "area": 50,
    "age": 15
  }]
}

找出 places 數(shù)組字段中至少同時包含一個滿足 “area 大于 100 且 age 小于 2” 的元素

const _ = db.command
db.collection('todos').where({
  places: _.elemMatch({
    area: _.gt(100),
    age: _.lt(2),
  })
})
.get()

注意*:如果不使用 elemMatch 而直接如下指定條件,則表示的是 places 數(shù)組字段中至少有一個元素的 area 字段大于 100 且 places 數(shù)組字段中至少有一個元素的 age 字段小于 2:

const _ = db.command
db.collection('todos').where({
  places: {
    area: _.gt(100),
    age: _.lt(2),
  }
})
.get()

示例代碼:數(shù)組元素都是普通數(shù)據(jù)類型的情況

假設(shè)集合示例數(shù)據(jù)如下:

{
  "_id": "a0",
  "scores": [60, 80, 90]
}

找出 scores 數(shù)組字段中至少同時包含一個滿足 “大于 80 且小于 100” 的元素

const _ = db.command
db.collection('todos').where({
  places: _.elemMatch(_.gt(80).lt(100))
})
.get()

Command.size(value: string): Command

支持端:小程序 2.8.3, 云函數(shù) 1.2.1, Web

更新操作符,用于數(shù)組字段的查詢篩選條件,要求數(shù)組長度為給定值

參數(shù)

value: string

返回值

Command

示例

找出 tags 數(shù)組字段長度為 2 的所有記錄

const _ = db.command
db.collection('todos').where({
  places: _.size(2)
})
.get({
  success: console.log,
  fail: console.error,
})


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號