在上一篇mongodb Aggregation聚合操作之addFields添加新字段中详细介绍了mongodb聚合操作中的addFields使用以及参数细节。本篇将开始介绍Aggregation聚合操作中的project 展示字段操作。
说明:
将文档和所请求的字段传递到管道中的下一个阶段。指定的字段可以是输入文档中的现有字段,也可以是新计算的字段。$project接受一个文档,该文档可以指定包含字段、抑制_id字段、添加新字段和重置现有字段的值。或者,您可以指定字段的排除。
语法:
{ $project: { <specification(s)> } }
1. 示例
初始化数据:
db.books.insertMany([{
"_id" : 1,
title: "abc123",
isbn: "0001122223334",
author: { last: "zzz", first: "aaa" },
copies: 5,
lastModified: "2016-07-28"
},
{
"_id" : 2,
title: "Baked Goods",
isbn: "9999999999999",
author: { last: "xyz", first: "abc", middle: "" },
copies: 2,
lastModified: "2017-07-21"
},
{
"_id" : 3,
title: "Ice Cream Cakes",
isbn: "8888888888888",
author: { last: "xyz", first: "abc", middle: "mmm" },
copies: 5,
lastModified: "2017-07-22"
}])
示例:
1.显示books集合中的title和author字段和id字段,其他字段不展示
db.books.aggregate( [ { $project : { title : 1 , author : 1 } } ] )
2.显示books集合中的title和author字段,其他字段不展示
db.books.aggregate( [ { $project : { _id: 0, title : 1 , author : 1 } } ] )
有条件地排除字段:从MongoDB 3.6开始,您可以在聚合表达式中使用变量REMOVE来有条件地抑制一个字段。
3.下面的$project阶段使用REMOVE变量来排除author.middle字段等于""记录:,如果该字段value值是"",那么该字段不做展示
db.books.aggregate( [
{
$project: {
title: 1,
"author.first": 1,
"author.last" : 1,
"author.middle": {
$cond: {
if: { $eq: [ "", "$author.middle" ] },
then: "$$REMOVE",
else: "$author.middle"
}
}
}
}
] )
结果:
{
"_id" : 1.0,
"title" : "abc123",
"author" : {
"last" : "zzz",
"first" : "aaa"
}
}
{
"_id" : 2.0,
"title" : "Baked Goods",
"author" : {
"last" : "xyz",
"first" : "abc"
}
}
{
"_id" : 3.0,
"title" : "Ice Cream Cakes",
"author" : {
"last" : "xyz",
"first" : "abc",
"middle" : "mmm"
}
}
4.包括计算字段
初始化数据:
db.test.insert({
"_id" : 1,
title: "abc123",
isbn: "0001122223334",
author: { last: "zzz", first: "aaa" },
copies: 5
})
下面的$project阶段添加了新的字段isbn、lastName和copiesSold:
db.test.aggregate(
[
{
$project: {
title: 1,
isbn: {
prefix: { $substr: [ "$isbn", 0, 3 ] },
group: { $substr: [ "$isbn", 3, 2 ] },
publisher: { $substr: [ "$isbn", 5, 4 ] },
title: { $substr: [ "$isbn", 9, 3 ] },
checkDigit: { $substr: [ "$isbn", 12, 1] }
},
lastName: "$author.last",
copiesSold: "$copies"
}
}
]
)
结果:
{
"_id" : 1.0,
"title" : "abc123",
"isbn" : {
"prefix" : "000",
"group" : "11",
"publisher" : "2222",
"title" : "333",
"checkDigit" : "4"
},
"lastName" : "zzz",
"copiesSold" : 5.0
}
5.项目新数组字段
初始化数据:db.test1.insert({ "_id" : ObjectId("55ad167f320c6be244eb3b95"), "x" : 1, "y" : 1 })
示例:
db.test1.aggregate( [ { $project: { myArray: [ "$x", "$y" ] } } ] )
结果:
{
"_id" : ObjectId("55ad167f320c6be244eb3b95"),
"myArray" : [
1.0,
1.0
]
}
网友评论