$project

修改输入文档的结构。可以用来重命名、增加或删除字段(域),也可以用于创建计算结果以及嵌套文档。

思考,现有books集合内容如下:

  1. db.books.insert(
  2. {
  3. "_id" : 1,
  4. title: "abc123",
  5. isbn: "0001122223334",
  6. author: { last: "zzz", first: "aaa" },
  7. copies: 5
  8. }
  9. )

1. 指定输出字段

db.books.aggregate( [ { $project: { title: 1, author: 1 } }] )

这样的话结果中就只还有_id,tilte和by_user三个字段了,默认情况下_id字段是被包含的,如果要想不包含_id话可以这样:

db.books.aggregate({ $project: { _id: 0, title: 1, author: 1 }})

注:和之前讲过的投影有点像db.books.find({},{'title':1,'author':1,'_id':0})

2. 输出嵌入式文档中field

db.books.aggregate({ $project: { _id: 0, title: 1, "author.last": 1 }})</div>输出:

  1. { "title" : "abc123", "author" : { "last" : "zzz" } }

3. 改变输出结构

db.books.aggregate({ $project: { _id: 0, title: 1, "lastName": "$author.last" }})</div>输出:

  1. { "title" : "abc123", "lastName" : "zzz" }

和sql语句里面的 select author.last as lastName from books类似

4. 计算 Fields

利用 $project 新增字段 isbn, lastName, and copiesSold:

substr语法:

  1. { $substr: [ <string>, <start>, <length> ] }

db.books.aggregate( [ { $project: { title: 1, isbn: { prefix: { $substr: [ "$isbn", 1, 3 ] }, }, lastName: "$author.last", copiesSold: "$copies" } } ])</div>输出:

  1. { "_id" : 1, "title" : "abc123", "isbn" : { "prefix" : "001" }, "lastName" : "zzz", "copiesSold" : 5 }

小结:

  • 指定输出字段

title: 1

  • 输出嵌入式文档中field

"author.last": 1

  • 改变输出结构

"lastName": "$author.last"

  • 计算 Fields

prefix: { $substr: [ "$isbn", 1, 3 ] }