May 20, 2021 WeChat Mini Program Development Document
3. Example code 1: Normal array
4. Example code 2: An array of objects
7. Example code: An array is the case of an array of objects
Support: Small program 2.8.3, cloud function 1.2.1, Web
Array query operator. A query filter for array fields that requires that the array field contain all elements of a given array.
Find records for tags array fields that contain both cloud and database
const _ = db.command
db.collection('todos').where({
tags: _.all(['cloud', 'database'])
})
.get({
success: console.log,
fail: console.error
})
If the array element is an object, you can match some of the object's fields with .elemMatch
Suppose there are fields that are defined as follows:
{
"type": string
"area": number
"age": number
}
Find out that the array field contains at least one element that satisfies "area is greater than 100 and age is less than 2" and an element that satisfies "type is mall and age is greater than 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,
})
Support: Small program 2.8.3, cloud function 1.2.1, Web
A query filter for array fields that requires the array to contain at least one element that meets all the criteria given by elemMatch
Match the condition
Suppose the sample data for the collection is as follows:
{
"_id": "a0",
"city": "x0",
"places": [{
"type": "garden",
"area": 300,
"age": 1
}, {
"type": "theatre",
"area": 50,
"age": 15
}]
}
Find out that the places array field contains at least one element that satisfies that the "area is greater than 100 and age is less than 2"
const _ = db.command
db.collection('todos').where({
places: _.elemMatch({
area: _.gt(100),
age: _.lt(2),
})
})
.get()
Note: If you do not specify the conditions as follows directly as follows using elemMatch, it means that the area field of at least one element in the places array field is greater than 100 and the age field of at least one element in the places array field is less than 2:
const _ = db.command
db.collection('todos').where({
places: {
area: _.gt(100),
age: _.lt(2),
}
})
.get()
Suppose the sample data for the collection is as follows:
{
"_id": "a0",
"scores": [60, 80, 90]
}
Find out that at least one element in the scores array field that meets "greater than 80 and less than 100" is included
const _ = db.command
db.collection('todos').where({
places: _.elemMatch(_.gt(80).lt(100))
})
.get()
Support: Small program 2.8.3, cloud function 1.2.1, Web
Update the operator, the query filter for array fields, to require the array length to be a given value
Find all records with a tags array field length of 2
const _ = db.command
db.collection('todos').where({
places: _.size(2)
})
.get({
success: console.log,
fail: console.error,
})