MongoDB-聚合操作$unwind

聚合管道阶段

$unwind: 展开数组字段

  • 格式: {$unwind:{path:<field>}}

在测试之前首先添加数据:

db.person.update({'name.firstName':'Jonathan'}, {$set:{tags:['html', 'js']}});
db.person.update({'name.firstName':'Amelie'}, {$set:{tags:'vue'}});

利用 $unwind 来展开数组:

db.person.aggregate([
    {
        $unwind:{
            path:'$tags'
        }
    }
]);

注意点

  • $unwind 会为数组中的每个元素创建一个新的文档
/* 1 */
{
  "_id" : ObjectId("62db6c62c94592381cf16c08"),
  "name" : {
    "firstName" : "Jonathan",
    "lastName" : "Lee"
  },
  "age" : 18,
  "book" : {
    "name" : "玩转HTML",
    "price" : 88
  },
  "tags" : "html"
}

/* 2 */
{
  "_id" : ObjectId("62db6c62c94592381cf16c08"),
  "name" : {
    "firstName" : "Jonathan",
    "lastName" : "Lee"
  },
  "age" : 18,
  "book" : {
    "name" : "玩转HTML",
    "price" : 88
  },
  "tags" : "js"
}

/* 3 */
{
  "_id" : ObjectId("62db6c62c94592381cf16c09"),
  "name" : {
    "firstName" : "Amelie",
    "lastName" : "BNTang"
  },
  "age" : 17,
  "book" : {
    "name" : "玩转JavaScript",
    "price" : 99
  },
  "tags" : "vue"
}
  • 可以通过 includeArrayIndex 属性添加展开之后的元素在原数组中的位置
db.person.aggregate([
    {
        $unwind:{
            path:'$tags',
            includeArrayIndex: 'index'
        }
    }
]);
  • 如果需要展开的字段不存在, 或者数组中没有元素, 或者为 null, 会被 unwind 剔除
db.person.insert([
    {name:{firstName:'san', lastName:'zhang'}, age:20},
    {name:{firstName:'si', lastName:'li'}, age:21, tags:[]},
    {name:{firstName:'wu', lastName:'wang'}, age:22, tags:null}
]);
db.person.aggregate([
    {
        $unwind:{
            path:'$tags',
            includeArrayIndex: 'index'
        }
    }
]);

运行得到的结果集如下,可以发现如上新添加的几条数据都没有被查询出来:

/* 1 */
{
  "_id" : ObjectId("62db6c62c94592381cf16c08"),
  "name" : {
    "firstName" : "Jonathan",
    "lastName" : "Lee"
  },
  "age" : 18,
  "book" : {
    "name" : "玩转HTML",
    "price" : 88
  },
  "tags" : "html",
  "index" : NumberLong(0)
}

/* 2 */
{
  "_id" : ObjectId("62db6c62c94592381cf16c08"),
  "name" : {
    "firstName" : "Jonathan",
    "lastName" : "Lee"
  },
  "age" : 18,
  "book" : {
    "name" : "玩转HTML",
    "price" : 88
  },
  "tags" : "js",
  "index" : NumberLong(1)
}

/* 3 */
{
  "_id" : ObjectId("62db6c62c94592381cf16c09"),
  "name" : {
    "firstName" : "Amelie",
    "lastName" : "BNTang"
  },
  "age" : 17,
  "book" : {
    "name" : "玩转JavaScript",
    "price" : 99
  },
  "tags" : "vue",
  "index" : null
}
  • 如果想让 unwind 不剔除不存在 / 没有元素 / 为 Null 的文档, 那么可以添加 preserveNullAndEmptyArrays 属性
db.person.aggregate([
    {
        $unwind:{
            path:'$tags',
            includeArrayIndex: 'index',
            preserveNullAndEmptyArrays: true
        }
    }
]);
posted @ 2022-07-24 15:23  BNTang  阅读(512)  评论(0)    收藏  举报