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();
});
还有一个子问题。
如果我可以将find
与aggregate
一起使用而不是查询,为什么要使用$match
答案 0 :(得分: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 $查找
db.activities.aggregate([
{ "$match": { "_id": ObjectId("5be46f266e4a182384b3ae6a") }},
{ "$lookup": {
"from": "users",
"localField": "_user",
"foreignField": "_id",
"as": "user"
}},
{ "$project": { "user.password": 0 }},
])