Mongo聚合-基于项目$ pushed到数组的查找

时间:2018-06-20 20:06:55

标签: mongodb aggregation-framework

我有一个Mongo /猫鼬查询:

res.locals.spellingTestResults =  await SpellingTest.aggregate([
        { $match : { "spellingId" : mongoose.Types.ObjectId(req.params.spellingId) } },
            { "$sort": { "user": 1 } },
            {
                "$lookup": {
                    "from": "users",
                    "localField": "user",
                    "foreignField": "_id",
                    "as": "user"
                }
            },
            {
                "$lookup": {
                    "from": "spellings",
                    "localField": "data.spellingId",
                    "foreignField": "_id",
                    "as": "spelling"
                }
            },
            { "$unwind": "$spelling" },
            { "$unwind": "$user" },
            { "$group" : {
                "_id": { "user": "$user" },
                "data": {
                    "$push": {
                        "numberOfSpellings": "$numberOfSpellings",
                        "spellingId": "$spellingId",
                        "wrongAnswers": "$wrongAnswers",
                        "created": "$created",
                        "rightAnswers": "$rightAnswers",
                        "score": "$score"
                    }
                }
            }
        },
        ]);

这将返回一个空数组。

但是,如果我删除第二个lookup,即

{
   "$lookup": {
      "from": "spellings",
      "localField": "data.spellingId",
      "foreignField": "_id",
      "as": "spelling"
      }
  },
  { "$unwind": "$spelling" },

然后我得到如下结果:

[ { _id:
      { user:
         { _id: 5ab79cc913840a359ff425f1,
           salt: '954c',
           hash: '3b1a',
           name: 'PageHill Class1 Child',
           userType: 'Child',
           email: '5ab79cc913840a359ff425f1@empty.com',
           __v: 0 } },
     data:
      [ { numberOfSpellings: 4,
          spellingId: 5b2aa9f02c63170baabe08db,
          wrongAnswers: [ 'of', 'spellings' ],
          created: 2018-06-20T19:26:08.832Z,
          rightAnswers: 2,
          score: 2 },
        { numberOfSpellings: 4,
          spellingId: 5b2aa9f02c63170baabe08db,
          wrongAnswers: [ 'spellings' ],
          created: 2018-06-20T19:39:48.398Z,
          rightAnswers: 3,
          score: 3 } 
    ] 
    }

我的问题是,如何使用以上data.spellingIdlookup中的值来填充该集合中的数据?

0 个答案:

没有答案