如何从Mongodb聚合中只返回一些字段($project),同时也使用$match、$lookup和$filter。

问题描述 投票:0回答:1

我非常接近从这个查询中得到我想要的东西......但我只想要返回部分字段,而现在它却返回了所有字段。

: 这是一个改进:我现在问的是如何归还 只在特定领域而我的类似 疑问 询问如何返回数据 起止日期之间

此外,请谁能提供一个答案,使用的是 MongoDB游乐场 与我的数据集,所以我可以尝试一下... ... 我不太明白如何给数据集 "命名",使它们能在操场上工作!

注册模式

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const RegisterSchema = new Schema({
    userId: {type: Schema.Types.ObjectId, required: true},
    accessToken: {type:String, required: true, default: null},
})
module.exports = Register = mongoose.model( 'register', RegisterSchema)

以下是一些寄存器数据

[
  {
    "_id": "5eac9e815fc57b07f5d0d29f",
    "userId": "5ea108babb65b800172b11be",
    "accessToken": "111"
  },
  {
    "_id": "5ecaeba3c7b910d3276df839",
    "userId": "5e6c2dddad72870c84f8476b",
    "accessToken": "222"
  }
]

下一个文档包含了与Register模式相关的数据,这些数据通过accessToken

通知

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const NotificationSchema = new Schema({
    accessToken: {type:String, required: true},
    summaryId: {type:Number, required: true},
    dateCreated: {type: Date, default: Date.now},

    // I don't want these returned in the final results
    dontWantThis1: {type:Number, required: true},
    dontWantThis2: {type:Number, required: true},
})
module.exports = Notification = mongoose.model( 'notification', NotificationSchema)

以下是一些通知数据

[{
    "_id": "5ebf0390c719e60004f42e74",
    "accessToken": "111",
    "summaryId": 1111,
    "dontWantThis1": 61,
    "dontWantThis2": 62,
    "dateCreated": "2020-04-17T00:00:00.000+00:00" }, 
  {
    "_id": "6ebf0390c719e60004f42e76",
    "accessToken": "222",
    "summaryId": 2221,
    "dontWantThis1": 71,
    "dontWantThis2": 72,
    "dateCreated": "2020-04-18T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e78",
    "accessToken": "111",
    "summaryId": 1112,
    "dontWantThis1": 611,
    "dontWantThis2": 622,
    "dateCreated": "2020-05-25T00:00:00.000+00:00" },
  {
    "_id": "6ebf0390c719e60004f42e80",
    "accessToken": "222",
    "summaryId": 2222,
    "dontWantThis1": 711,
    "dontWantThis2": 722,
    "dateCreated": "2020-05-26T00:00:00.000+00:00" }
]

工作,返回这两个日期之间的数据,但。

这段代码返回所有内容,包括'dontWantThis1'和'dontWantThis2'。

我不希望字段前缀为'dontWantThis'--但这只是为了显示我不想要的字段......。我并不是真的要排除前面带有'dontWantThis'的字段......它们可以被命名为'foo'或'apple'或'dog',它们只是以这种方式命名来表明我不想要它们。


        // make sure the input dates are REALLY date objects
        // I only want to see notifications for the month of May (in this example)
        var dateStart = new Date('2020-05-01T00:00:00.000+00:00');
        var dateEnd = new Date('2020-05-30T00:00:00.000+00:00');     

        var match = {$match: { userId: mongoose.Types.ObjectId(userId) } };

        var lookup ={
            $lookup:
            {
                from: "my_Notifications",
                localField: "accessToken",
                foreignField: "accessToken",
                as: "notifications"
            }
        };

        var dateCondition = { $and: [
            { $gte: [ "$$item.dateCreated", dateStart ] },
            { $lte: [ "$$item.dateCreated", dateEnd ] }
          ]}  

        var project = {
            $project: {
                notifications: {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    } } }
        };

        var agg = [
            match,
            lookup,
            project
        ];

        Register.aggregate(agg)
        .then( ..... )

试试1

我想我可以做这样的事情,但它仍然返回所有的通知字段。

        var project = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,

                notifications : {
                    $filter: {
                    input: "$notifications",
                    as: "item",
                    cond: dateCondition
                    },
            }}
        };

解决方法

我创建了另一个投影,并将其添加到管道中。

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };


        var agg = [
            match,
            lookup,
            project,
            project2,
        ];

谢谢! - 我非常接近得到我想要的查询结果...

mongodb filtering lookup aggregation projection
1个回答
0
投票

https:/stackoverflow.comusers6635464ngshravil-py 是准确的。

我又创建了一个投影。

        var project2 = {
            $project: {
                "_id": 1,
                "userId": 1,
                "accessToken":1,
                "count":{$size:"$notifications"},
                "notifications._id":1,
                "notifications.summaryId": 1,
                "notifications.dateCreated":1,
                "notifications.dateProcessed":1,
            }
        };

然后把它添加到我的聚合管道中。

        var agg = [
            match,
            lookup,
            project,
            project2,
        ];

成功了!-- 谢谢你 https:/stackoverflow.comusers6635464ngshravil-py。


0
投票

你需要转换 notifications.dateCreatedISODate,因为你的日期是字符串,通过使用 $dateFromString$map 我建议你这样做,因为我不认为你可以用字符串格式做日期比较。另外,请确保 dateStartdateEnd 也应在 ISODate 格式。

而你需要两个 $project 操作员,以实现这一目的。另外,我也没有看到任何字段带着 userAccessToken我想,它是 accessToken. 查看下面的查询。

db.Register.aggregate([
  {
    $lookup: {
      from: "my_Notifications",
      localField: "accessToken",
      foreignField: "accessToken",
      as: "notifications"
    }
  },
  {
    $project: {
      "_id": 1,
      "userId": 1,
      "accessToken": 1,
      notifications: {
        $map: {
          input: "$notifications",
          as: "n",
          in: {
            "_id": "$$n._id",
            "summaryId": "$$n.summaryId",
            "dateCreated": {
              $dateFromString: {
                dateString: "$$n.dateCreated"
              }
            }
          }
        }
      }
    }
  },
  {
    $project: {
      "userId": 1,
      "accessToken": 1,
      "notifications": {
        $filter: {
          input: "$notifications",
          as: "item",
          cond: {
            $and: [
              {
                $gte: [
                  "$$item.dateCreated",
                  ISODate("2020-05-24T00:00:00Z")
                ]
              },
              {
                $lte: [
                  "$$item.dateCreated",
                  ISODate("2020-05-26T00:00:00Z")
                ]
              }
            ]
          }
        }
      }
    }
  },
  {
    $set: {
      "count": {
        $size: "$notifications"
      }
    }
  }
])

MongoPlayGroundLink

© www.soinside.com 2019 - 2024. All rights reserved.