MongoDB在子文档数组上的查询和投影也返回另一个文档的数组

时间:2019-01-13 16:19:05

标签: node.js mongodb express

我试图查询嵌入的子文档,然后仅通过projection返回该子文档中的数组。查询后,您可以选择要通过投影返回的字段。我想使用本机功能,因为这是可行且最简洁的方法。问题在于它在两个文档中返回数组。

我尝试了其他查询和投影选项,但没有结果。


 用户模型

             // Define station schema
             const stationSchema = new mongoose.Schema({
                mac: String,
                stationName: String,
                syncReadings: Boolean,
                temperature: Array,
                humidity: Array,
                measures: [{
                    date: Date,
                    temperature: Number,
                    humidity: Number
                }],
                lastUpdated: Date
            });

            // Define user schema
            var userSchema = mongoose.Schema({

                apiKey: String,
                stations : [stationSchema]

            },  {
                    usePushEach: true 
                }
            );

api调用

       app.get('/api/stations/:stationName/measures',function(req, res, next) {

        var user = {
            apiKey: req.user.apiKey
        }

        const query = {
            apiKey: user.apiKey,
            'stations.stationName': req.params.stationName
        }

        const options = {
            'stations.$.measures': 1,
        }

        User.findOne(query, options)
        .exec()
        .then(stations => {     
            res.status(200).send(stations)
        })
        .catch(err => {
            console.log(err);
            res.status(400).send(err);
        })

    });

预期结果

   {
        "_id": "5c39c99356bbf002fb092ce9",
        "stations": [
            {
                "stationName": "livingroom",
                "measures": [
                    {
                        "humidity": 60,
                        "temperature": 20,
                        "date": "2019-01-12T22:49:45.468Z",
                        "_id": "5c3a6f09fd357611f8d078a0"
                    },
                    {
                        "humidity": 60,
                        "temperature": 20,
                        "date": "2019-01-12T22:49:46.500Z",
                        "_id": "5c3a6f0afd357611f8d078a1"
                    },
                    {
                        "humidity": 60,
                        "temperature": 20,
                        "date": "2019-01-12T22:49:47.041Z",
                        "_id": "5c3a6f0bfd357611f8d078a2"
                    }
                ]
            }
        ]
    }

实际结果

   {
        "_id": "5c39c99356bbf002fb092ce9",
        "stations": [
            {
                "stationName": "livingroom",
                "measures": [
                    {
                        "humidity": 60,
                        "temperature": 20,
                        "date": "2019-01-12T22:49:45.468Z",
                        "_id": "5c3a6f09fd357611f8d078a0"
                    },
                    {
                        "humidity": 60,
                        "temperature": 20,
                        "date": "2019-01-12T22:49:46.500Z",
                        "_id": "5c3a6f0afd357611f8d078a1"
                    },
                    {
                        "humidity": 60,
                        "temperature": 20,
                        "date": "2019-01-12T22:49:47.041Z",
                        "_id": "5c3a6f0bfd357611f8d078a2"
                    }
                ]
            },
******************************************************
 // this whole object should not be returned
            {
              "stationName": "office",
                "measures": [] 
            }
******************************************************
        ]
    }

修改 以下关于聚合的答案有效,但我仍然觉得很奇怪,因为我需要那么多代码。如果在我的普通查询之后,使用“ .stations [0] .measures”而不是整个聚合管道得到相同的结果:

.then(stations => {     
    res.status(200).send(stations.stations[0].measures)
})

我阅读代码的方式,上面的代码与以下代码完全相同:

const options = {'stations.$.measures': 1}

美元符号放在索引0的位置,因为那是与查询部分相匹配的站点的索引:stationName:“ livingroom”

有人可以解释吗?

2 个答案:

答案 0 :(得分:1)

这没有用mongoose来描述,但是它将在1个或多个文档中的一组站点中找到特定的站点名称,并且仅返回measures数组:

db.foo.aggregate([
// First, find the docs we are looking for:
{$match: {"stations.stationName": "livingroom"}}

// Got the doc; now need to fish out ONLY the desired station.  The filter will
// will return an array so use arrayElemAt 0 to extract the object at offset 0.
// Call this intermediate qqq:
,{$project: { qqq:
      {$arrayElemAt: [
          { $filter: {
            input: "$stations",
            as: "z",
            cond: { $eq: [ "$$z.stationName", "livingroom" ] }
      }}, 0]
      } 
}}

// Lastly, just project measures and not _id from this object:
,{$project: { _id:0, measures: "$qqq.measures" }}
                  ]);

答案 1 :(得分:0)

$elemMatch运算符将查询结果中数组字段的内容限制为仅包含与$ elemMatch条件匹配的第一个元素。

在“选择查询”中尝试$ elemMatch,如下所示:

const query = {
     apiKey: user.apiKey,
     'stations.stationName': req.params.stationName
}
const options = {
   'stations' : {$elemMatch: { 'stationName' : req.params.stationName }}
}