1.Array Expressions(数组表达式)
(1). $filter
3.2版中的新增功能,根据指定的条件选择要返回的数组的子集。返回只包含与条件匹配的元素的数组。返回的元素按原始顺序排列。
插入基础数据
db.filter_sales.insert([
{
_id: 0,
items: [
{ item_id: 43, quantity: 2, price: 10 },
{ item_id: 2, quantity: 1, price: 240 }
]
},
{
_id: 1,
items: [
{ item_id: 23, quantity: 3, price: 110 },
{ item_id: 103, quantity: 4, price: 5 },
{ item_id: 38, quantity: 1, price: 300 }
]
},
{
_id: 2,
items: [
{ item_id: 4, quantity: 1, price: 23 }
]
}])
下面的示例过滤items数组,使其仅包含价格大于或等于100的文档:
db.filter_sales.aggregate([
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: [ "$$item.price", 100 ] }
}
}
}
}
])
$filter的第一个选项是input。对于input,我们只需指定一个数组
$filter的第二个选项是as,可选的。表示输入数组的每个元素的变量的名称。如果未指定名称,则变量名默认为。
$filter的第三个选项是cond,指定条件
(2). $arrayElemAt
3.2版中的新增功能。返回指定数组索引处的元素。
插入基础数据
db.arrayelemat_users13.insert([
{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] },
{ "_id" : 2, "name" : "li", favorites: [ "apples", "pudding", "pie" ] },
{ "_id" : 3, "name" : "ahn", favorites: [ "pears", "pecans", "chocolate", "cherries" ] },
{ "_id" : 4, "name" : "ty", favorites: [ "ice cream" ] }
])
以下示例返回favorites数组中的第一个和最后一个元素:
db.arrayelemat_users13.aggregate([
{
$project:
{
name: 1,
first: { $arrayElemAt: [ "$favorites", 0 ] },
last: { $arrayElemAt: [ "$favorites", -1 ] }
}
}
])
(3). $slice
3.2版中的新增功能。返回数组的子集。
插入基础数据
db.slice_users14.insert([
{ "_id" : 1, "name" : "dave123", favorites: [ "chocolate", "cake", "butter", "apples" ] },
{ "_id" : 2, "name" : "li", favorites: [ "apples", "pudding", "pie" ] },
{ "_id" : 3, "name" : "ahn", favorites: [ "pears", "pecans", "chocolate", "cherries" ] },
{ "_id" : 4, "name" : "ty", favorites: [ "ice cream" ] }
])
以下示例最多为每个用户返回favorites数组中的前三个元素:
db.slice_users14.aggregate([
{ $project: { name: 1, threeFavorites: { $slice: [ "$favorites", 3 ] } } }
])
(4). $size
计算并返回数组中的项目总数。
插入基础数据
db.size_inventory.insert([
{ "_id" : 1, "item" : "ABC1", "description" : "product 1", colors: [ "blue", "black", "red" ] },
{ "_id" : 2, "item" : "ABC2", "description" : "product 2", colors: [ "purple" ] },
{ "_id" : 3, "item" : "XYZ1", "description" : "product 3", colors: [ ] },
{ "_id" : 4, "item" : "ZZZ1", "description" : "product 4 - missing colors" },
{ "_id" : 5, "item" : "ZZZ2", "description" : "product 5 - colors is string", colors: "blue,red" }
])
以下聚合管道操作使用 $size 运算符返回colors数组中的元素数:
db.size_inventory.aggregate([
{
$project: {
item: 1,
numberOfColors: { $cond: { if: { $isArray: "$colors" }, then: { $size: "$colors" }, else: "NA"} }
}
}
] )