数组中只返回一个元素

时间:2016-06-20 12:16:24

标签: arrays mongodb meteor filter

我正在尝试使用meteor从MongoDB数据库中查找元素。 我设法过滤并遍历我的数组的结构,但结果是单个元素,而不是所有符合条件的元素。

查询:

var json = Tests1VerlIR.find({}, {fields: {entries: {$elemMatch: {'payload.id': {$eq: this.params._id}} } } }).fetch();
this.response.setHeader('Content-Type', 'application/json');
this.response.end(JSON.stringify(json));

数据结构:

{"entries":
   [{"method":"POST",
   "source":"ex",
   "path":"/ex",
   "time":1464615406900,
   "payload":        
        {"slot_frame_number":"4",
         "slot_HTUTemp":"2306",
         "data":"0400f008561655270209a314",
         "slot_BMEPres":"10069",
         "slot_HTUHumi":"5283",
         "slot_BMETemp":"2288",
         "time":"1464615404",
         "device":"79",
         "slot_BMEHumi":"5718",
         "signal":"7.22",
         "id":"2"},
   "_id":"574c41ee578d01af3664cbaf"},
   {"method":"POST",
   "source":"ex",
   "path":"/ex",
   "time":1464615406900,
   "payload":        
        {"slot_frame_number":"4",
         "slot_HTUTemp":"2306",
         "data":"0400f008561655270209a314",
         "slot_BMEPres":"10069",
         "slot_HTUHumi":"5283",
         "slot_BMETemp":"2288",
         "time":"1464615404",
         "device":"79",
         "slot_BMEHumi":"5718",
         "signal":"7.22",
         "id":"2"},
   "_id":"574c41ee578d01af3664cbaf"}, {...}]}

回应:

[
    {
        "_id":
        {
            "_str": "576155d7a605348159cd1f1a"
        },
        "entries":
        [
            {
                "method": "POST",
                "source": "ex",
                "path": "/ex",
                "time": 1464615406900,
                "payload":
                {
                     "slot_frame_number":"4",
                     "slot_HTUTemp":"2306",
                     "data":"0400f008561655270209a314",
                     "slot_BMEPres":"10069",
                     "slot_HTUHumi":"5283",
                     "slot_BMETemp":"2288",
                     "time":"1464615404",
                     "device":"79",
                     "slot_BMEHumi":"5718",
                     "signal":"7.22",
                     "id":"2"
                },
                "_id": "574c41ee578d01af3664cbaf"
            }
        ]
    }
]

2 个答案:

答案 0 :(得分:1)

您不能以任何形式的基本.find()查询返回符合条件的数组的多个元素。要匹配多个元素,您需要使用.aggregate()方法。

参考this link

Tests1VerlIR.aggregate([
{ "$match": { "entries.payload.id": "2" } },

    // Unwind the array to denormalize
    { "$unwind": "$entries" },

    // Match specific array elements
    { "$match": { "entries.payload.id": "2" } },

    // Group back to array form
    { "$group": {
        "_id": "$_id",
        "entries": { "$push": "$entries" }
    }}
])

答案 1 :(得分:-1)

解决方案:

var json = Tests1VerlIR.aggregate({"$unwind": "$entries"}, {$match: {'entries.payload.id': this.params._id} });
相关问题