简体   繁体   English

MongoDB查找所有匹配数组,返回的不仅是唯一的

[英]MongoDB Find All Matching array, return all not just unique

I have a user collection. 我有一个用户集合。 In that collection each user when they enter a prize will have the prize id stored on their profile. 在该集合中,每个用户输入奖品时,奖品ID将存储在其个人资料中。 Export of a typical user document below 在下面导出典型的用户文档

{ 
    "_id" : ObjectId("5aacff47c67f99103bcbf693"), 
    "firstName" : "Test", 
    "lastName" : "Test", 
    "password" : "$2a$10$mJjzPFWuYPmK8A07nc284O8g9SStFpuaVzfyWOZgaCmVaomIxk5qO", 
    "email" : "test1@test.com", 
    "points" : NumberInt(6), 
    "prizes" : [
        ObjectId("5aafd1673a5b2cb294b69620"), 
        ObjectId("5aafd1673a5b2cb294b69620"), 
        ObjectId("5aafd1673a5b2cb294b69620"), 
        ObjectId("5aafd1673a5b2cb294b69620"), 
        ObjectId("5aafd1673a5b2cb294b69620"), 
        ObjectId("5ab28ca784aa6390aa5a1dba")
    ], 
    "messages" : [

    ], 
    "__v" : NumberInt(26)
}

I wrote a api call that when a user lands on their account page, it finds the user and returns their prize entires (array of prizes). 我写了一个api调用,当用户登陆其帐户页面时,它将找到该用户并返回其全部奖励(奖励阵列)。 I then want to use these to query the DB to find the title/content of each entry so it can be displayed on the front end. 然后,我想使用这些查询数据库来查找每个条目的标题/内容,以便可以将其显示在前端。

I've done this two ways 我已经做到了两种方式

var prizes = user.prizes

       //mongo

       ids = prizes.map(function(el) { return mongoose.Types.ObjectId(el) })

       Prize.aggregate([
        { $match: { "_id": { "$in": ids } } }

      ], function(err, ret){
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });

        }
          console.log(ret)
      }
    )

or 要么

Prize.find( { _id: prizes }, { title: 1, content: 1 }, function(err, ret){
        if (err) {
            return res.status(500).json({
                title: 'An error occurred',
                error: err
            });

        }
console.log(ret)



       })

Now the difficult part, both of these operations only return unique documents, (2) and not the 6 I wanted. 现在最困难的部分是,这两个操作仅返回唯一的文档(2),而不返回我想要的6个文档。

I wanted to find for every entry id then return that prize id's title and content , without caring if unique or not or have a count in response, so giving my user above it would return 我想查找每个条目ID,然后返回该奖项ID的标题和内容,而不关心是否唯一或是否有响应,因此给我高于它的用户将返回

{1x unique doc count 4} {1x unique doc, count 1} {1x唯一文档数4} {1x唯一文档数1}

or return 6 responses. 或返回6个响应。

Even when I used the .count(), it only counted 2. I know I must be going about this the wrong way, as mongo is correct in that i'm asking it to find the documents matching the id's I pass it and it finds the 2 matching id's and serves them up. 即使当我使用.count()时,它也只计为2。我知道我一定会以错误的方式进行处理,因为mongo是正确的,因为我要它查找与id匹配的文档,然后将它传递给它找到两个匹配的ID并将其投放。

Am i almost breaking it's functionality by asking it to do something different? 我是否通过要求它做一些不同的事情来破坏它的功能? Other options? 还有其他选择吗? Wrap it up in a for each in node and query each id manually and push to an array? 将其包装在每个in节点的a中,然后手动查询每个id并推送到数组?

Get the prizes for specific user. 获取特定用户的奖品。

$unwind and $group to count no of prizes followed by $lookup to get prizes fields in 3.4. $unwind$group不计算奖品数,然后$lookup获取3.4中的奖品字段。

User.aggregate([
  {"$match":{"_id":mongoose.Types.ObjectId(userid)}},
  {"$unwind":"$prizes"},
  {"$group":{"_id":"$prizes","count":{"$sum":1}}},
  {"$lookup":{
    "from":"prizes", // name of the prize collection
    "localField":"_id", 
    "foreignField":"_id",
    "as":"prizes"
  }},
  {"$addFields":{"prizes":{"$arrayElemAt":["$prizes",0]}}}
])

Get both the user and prizes. 获得用户和奖品。

Use $lookup followed by $map to keep the fields from lookup and use $filter with $size to count the no of prizes for each id in 3.4. 使用$lookup$map来阻止字段查找,并使用$filter$size来计算3.4中每个id的奖品数量。

Something like 就像是

User.aggregate([
  {"$match":{"_id":mongoose.Types.ObjectId(userid)}},
  {"$lookup":{
    "from":"prizes", // name of the prize collection
    "localField":"prizes",
    "foreignField":"_id",
    "as":"prizeinfo"
  }},
  {"$addFields":{
    "prizeinfo":{
      "$map":{
        "input":"$prizeinfo",
        "as":"pi",
        "in":{
          "title":"$$pi.title",
          "content":"$$pi.content",
          "count":{
            "$size":{
              "$filter":{
                "input":"$prizes",
                "as":"p",
                "cond":{"$eq":["$$pi._id","$$p"]}
              }
            }
          }
        }
      }
    }
  }}
])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM