MongoDB-聚合操作$unwind

网友投稿 920 2022-10-11

MongoDB-聚合操作$unwind

MongoDB-聚合操作$unwind

聚合管道阶段

$unwind: 展开数组字段

格式:​​{$unwind:{path:}}​​

在测试之前首先添加数据

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 } }]);

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:LightBulb是一个开源的python框架用于审计web应用程序防火墙
下一篇:MongoDB-聚合操作$lookup
相关文章

 发表评论

暂时没有评论,来抢沙发吧~