社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  MongoDB

mongodb query and projection on subdocument数组还返回另一个文档的数组

Mark de Jonge • 7 年前 • 2315 次点击  

我试图查询嵌入的子文档,然后仅通过 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”

有人能解释吗?

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40753
文章 [ 2 ]  |  最新文章 7 年前
the_mahasagar
Reply   •   1 楼
the_mahasagar    7 年前

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

在选择查询中尝试$elemmatch,如下所示:

const query = {
     apiKey: user.apiKey,
     'stations.stationName': req.params.stationName
}
const options = {
   'stations' : {$elemMatch: { 'stationName' : req.params.stationName }}
}
Buzz Moschetti
Reply   •   2 楼
Buzz Moschetti    7 年前

这不是用 mongoose 但这将在一个或多个文档中的站点数组中找到一个特定的站点名称,并且只返回 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" }}
                  ]);