【发布时间】: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