首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Mongoose/MongoDB聚合- $match $unwind $match不工作?

Mongoose/MongoDB聚合- $match $unwind $match不工作?
EN

Stack Overflow用户
提问于 2014-08-01 06:38:33
回答 1查看 1.3K关注 0票数 1

如何将此存档-视图-聚合更改为也聚合from.view.archive : true?

..while阻止聚合重复的messages..if发件人用户(sessionUser)存在于To数组中,然后仅获取其中一条消息。

代码语言:javascript
运行
复制
 if (archive === true) {
  console.log('archive === ' + true);

  Models.Message.aggregate([

     // Match documents
     { "$match": {
          "to": { 
              "$elemMatch": {
                 "username": req.session.username,
                 "view.archive": true,
                 "view.bin": false
              }
          },
          "$or": messagingquery
     }},

     // Unwind to de-normalize
     { "$unwind": "$to" },

     // Match the array elements      
     { "$match": {
         "to.username": req.session.username,
         "to.view.archive": true,
         "to.view.bin": false
     }},

     // Group back to the original document
     { "$group": {
         "_id": "$_id",
         "from": { "$first": "$from" },
         "to": { "$push": "$to" },
         "message": { "$first": "$message" },
         "timesent": { "$first": "$timesent" },
         "replies": { "$first": "$replies" },
         "messaging": { "$first": "$messaging" }
     }},

     // Sort by updated, most recent first (descending)
     {"$sort": {"updated": -1}}

  ], function (err, messages) {

    if (err) {
      console.log(err);
      res.send(err);
    }

    res.json({
      messages : messages,
      sessionUser: sessionUser
    });

  });

}

对于MesageSchema的From和To数组,UserMessageSchema如下所示:

代码语言:javascript
运行
复制
var UserMessageSchema   = new Schema({
  user        : { "type": Schema.ObjectId, "ref": "User" },
  username    : String,
  view : {
    inbox       : Boolean,
    outbox      : Boolean,
    archive     : Boolean,
    bin         : Boolean
  },
  read : {
    marked      : { "type": Boolean, default: false },
    datetime    : Date
  },
    updated   : Date
});
EN

回答 1

Stack Overflow用户

发布于 2014-08-01 23:13:47

我觉得我一定是误解了某些情况,但听起来您应该能够在第一个比赛阶段添加一个简单的$or

代码语言:javascript
运行
复制
{ "$match": {
    "$or" : [
        {
            "to": { 
                  "$elemMatch": {
                      "username": req.session.username,
                      "view.archive": true,
                      "view.bin": false
                  }
            }
        },
        {
            "from" : {
                "$elemMatch" : {
                    "username" : req.session.username,
                    "view.archive": true,
                }
            }
        }
    ],
        "$or": messagingquery
 }}

复制不能由$match阶段产生,因为$match根据条件过滤文档。复制是从哪里来的,“复制”到底是如何定义的?

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25070082

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档