与同一集合中的聚集和查找猫鼬

时间:2018-12-31 17:23:12

标签: mongodb mongoose

我在同一集合中有两种文档类型,使用区分键将它们分开。我需要对两个文档中的字段进行汇总查找。这是文档架构的样子

const Member = Base.discriminator('Member', new mongoose.Schema({
_id: String,
firstName: {type: String,default: ""},
lastName: {type: String,default: ""},
member: {
     type: mongoose.Schema.Types.String,
     ref: 'Member'
      }
}));

const Statement= Base.discriminator('Member', new mongoose.Schema({
_id: String,
firstName: {type: String,default: ""},
lastName: {type: String,default: ""}
}));

我想做的是获取所有语句并将成员的名字和姓氏填充为一个字段

这是我尝试过的缩写,但查找不返回任何内容

    var pipeline = [{
  "$lookup": {
    "from": "data",
    "localField": "member",
    "foreignField": "_id",
    "as": "memberData"
  }
},  {
    $project: {
    //statement fields go here, removed for simplicity
    "name": { $concat: ["$memberData.firstName", " ", "$memberData.lastName"] }
  }
}];

var _allStatements = await Statement.aggregate(pipeline);

我正在做其他所有事情,但已删除它们,只是尝试使此查找工作。感谢您的帮助

编辑:示例文档

{
"_id" : ObjectId("5b8997306668b939489a773b"),
"batch" : "1221",
"paymentAmount" : 120,
"cash" : false,
"__type" : "Statement",
"member" : "11e0cbcf-9682-4163-9692-a73e4a33689d"
}

{
"_id" : "11e0cbcf-9682-4163-9692-a73e4a33689d",
"firstName" : "John",
"lastName" : "Doe",
"__type" : "Member",
}

预期输出:

{
"batch" : "1221",
"paymentAmount" : 120,
"cash" : false,
"name":"John Doe"
}

0 个答案:

没有答案