【问题标题】:limit fields in $lookup aggregation限制 $lookup 聚合中的字段
【发布时间】:2019-04-18 18:42:53
【问题描述】:

MongoDB 数据库版本 3.4.18。

我想合并来自外部集合的数据,但我不想拥有它的所有键,我想做一个限制,像这样:

db.users.find({}, {password:0}, (err, docs) => {});

这是我的聚合查询:

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

我还有一个子问题。

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

【问题讨论】:

  • 如果您使用的是 mongodb 3.6,请替换为下面的 $lookup 阶段。 { "$lookup": { "from": "users", "let": { "user": "$_user" }, "pipeline": [ { "$match": { "$expr": { "$eq": ["$_id", "$$user"] }}}, { "$project": { "password": 0 }} ], "as": "user" }}
  • 你能用我的代码来回答吗?我收到未定义的..
  • 如果您的上述聚合查询正在运行并且您使用的是 mongodb 3.6,那么只需将 $lookup 阶段替换为上述阶段即可。
  • 我在 3.4,应该更新,或者有什么东西可以同时工作?

标签: mongodb mongodb-query aggregation-framework


【解决方案1】:

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

标准 MongoDB $lookup

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

【讨论】:

  • 这不起作用。这限制了原始集合的字段。
  • @Raz 只需将0$project 中不需要的字段一起使用。类似{ $project: { fieldName: 0, fieldName2: 0 }}
猜你喜欢
  • 2018-08-06
  • 2019-01-27
  • 2019-11-08
  • 2018-04-26
  • 2016-07-16
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 2020-08-19
相关资源
最近更新 更多