MongoDB 聚合管道中使用数组表达式运算符(获取数组元素)

数组表达式运算符主要用于文档中数组的操作,本篇我们主要介绍数组表达式运算符中用于获取数组元素的操作,下面我们进行详细介绍:

一、准备工作

初始化成员数据

db.persons.insertMany([
    { "_id" : "1001", "name" : "张三", "fruits" : [ "apple", "orange" ] },
    { "_id" : "1002", "name" : "李四", "fruits" : [ "banana", "apple" ] },
    { "_id" : "1003", "name" : "王五", "fruits" : [ "banana", "apple", "orange" ] },
    { "_id" : "1004", "name" : "赵六", "fruits" : [ ] },
    { "_id" : "1005", "name" : "田七" },
])

二、获取数组中指定元素($arrayElemAt)

语法:{ $arrayElemAt: [ , ] }

        获取数组中指定索引位置的元素

:代表的是数组

:代表的是索引,索引为正数代表的是从前往后查找元素、为负数代表的是从后往前查找元素

数组的索引从0开始,最大值为数组的长度-1

例子1:找到每个人最喜欢吃的第一个水果

db.persons.aggregate([
    {
        $project: {
            "name": 1,
            "firstFruit": { $arrayElemAt: [ "$fruits", 0 ] }
        }
    }
])

聚合查询的结果如下:

{ "_id" : "1001", "name" : "张三", "firstFruit" : "apple" }
{ "_id" : "1002", "name" : "李四", "firstFruit" : "banana" }
{ "_id" : "1003", "name" : "王五", "firstFruit" : "banana" }
{ "_id" : "1004", "name" : "赵六" }
{ "_id" : "1005", "name" : "田七", "firstFruit" : null }

字段未定义时,结果为null,

索引超过数组边界则不返回结果。

例子2:找到每个人最喜欢吃的最后一个水果

db.persons.aggregate([
    {
        $project: {
            "name": 1,
            "lastFruit": { $arrayElemAt: [ "$fruits", -1 ] }
        }
    }
])

聚合查询的结果如下:

{ "_id" : "1001", "name" : "张三", "lastFruit" : "orange" }
{ "_id" : "1002", "name" : "李四", "lastFruit" : "apple" }
{ "_id" : "1003", "name" : "王五", "lastFruit" : "orange" }
{ "_id" : "1004", "name" : "赵六" }
{ "_id" : "1005", "name" : "田七", "lastFruit" : null }

索引为负数代表的是从后往前查找元素

 三、获取数组中第一个元素($first)

语法:{ $first: }

        获取数组中第一个元素

例子:找到每个人最喜欢吃的第一个水果

db.persons.aggregate([
    {
        $project: {
            "name": 1,
            "firstFruit": { $first: "$fruits" }
        }
    }
])

等效于:

db.persons.aggregate([
    {
        $project: {
            "name": 1,
            "firstFruit": { $arrayElemAt: [ "$fruits", 0 ] }
        }
    }
])

聚合查询的结果如下:

{ "_id" : "1001", "name" : "张三", "firstFruit" : "apple" }
{ "_id" : "1002", "name" : "李四", "firstFruit" : "banana" }
{ "_id" : "1003", "name" : "王五", "firstFruit" : "banana" }
{ "_id" : "1004", "name" : "赵六" }
{ "_id" : "1005", "name" : "田七", "firstFruit" : null }

 四、获取数组中最后一个元素($last)

语法:{ $last: }

        获取数组中最后一个元素

例子:找到每个人最喜欢吃的最后一个水果

db.persons.aggregate([
    {
        $project: {
            "name": 1,
            "lastFruit": { $last: "$fruits" }
        }
    }
])

等效于:

db.persons.aggregate([
    {
        $project: {
            "name": 1,
            "lastFruit": { $arrayElemAt: [ "$fruits", -1 ] }
        }
    }
])

聚合查询的结果如下:

{ "_id" : "1001", "name" : "张三", "lastFruit" : "orange" }
{ "_id" : "1002", "name" : "李四", "lastFruit" : "apple" }
{ "_id" : "1003", "name" : "王五", "lastFruit" : "orange" }
{ "_id" : "1004", "name" : "赵六" }
{ "_id" : "1005", "name" : "田七", "lastFruit" : null }

你可能感兴趣的:(MongoDB,mongodb,数据库,nosql)