限制 $lookup 聚合中的字段

Raz*_*Raz 1 mongodb mongodb-query aggregation-framework

MongoDB 数据库版本 3.4.18。

我想合并来自外部集合的数据,但我不想拥有所有键,我想做出限制,如下所示:

db.users.find({}, {password:0}, (err, docs) => {});
Run Code Online (Sandbox Code Playgroud)

这是我的聚合查询:

let query = [
  {
    // match from first collection (activities)
    $match: {
      "_id": ObjectId("5be46f266e4a182384b3ae6a")
    }
  },
  {
    // limit fields from first collection (activities)
    $project: {
      "_user": 1,
      date: 1
    }
  },
  {
    // join a foreign collection - but how to avoice the password key? for example.
    $lookup: {
      from: "users",
      localField: "_user",
      foreignField: "_id",
      as: "user"
    }
  }
];
db.activities.aggregate(query, (err, docs) => {
  console.log(docs[0].user);
  return cast.ok();
});
Run Code Online (Sandbox Code Playgroud)

我有一个小问题。

find如果我可以使用aggregate,$match而不是查询,为什么要使用

Ash*_*shh 5

MongoDB 3.6,“嵌套”$lookup

db.activities.aggregate([
  { "$match": { "_id": ObjectId("5be46f266e4a182384b3ae6a") }},
  { "$lookup": {
    "from": "users",
    "let": { "user": "$_user" },
    "pipeline": [
      { "$match": { "$expr": { "$eq": ["$_id", "$$user"] }}},
      { "$project": { "password": 0 }}
    ],
    "as": "user"
  }},
  { "$project": { "user": 1, "date": 1 }},
])
Run Code Online (Sandbox Code Playgroud)

标准 MongoDB $lookup

db.activities.aggregate([
  { "$match": { "_id": ObjectId("5be46f266e4a182384b3ae6a") }},
  { "$lookup": {
    "from": "users",
    "localField": "_user",
    "foreignField": "_id",
    "as": "user"
  }},
  { "$project": { "user.password": 0 }},
])
Run Code Online (Sandbox Code Playgroud)