仅返回嵌套文档数组中的匹配子文档

时间:2018-12-11 12:06:54

标签: mongodb mongoose

我有一个猫鼬的文档,带有嵌套的文档数组。我的文档具有以下结构:

Semigroup

这会在我的数据库中产生以下数据:

$subquery = DB::table('message')
    ->selectRaw("if(sender_id = ?, receiver_id, sender_id) AS id")
    ->distinct()
    ->where(function($query){
        $query
            ->where('receiver_id', '?')
            ->orWhere('sender_id', '?');
    })
    ->toSql();

$query = DB::table('user')
    ->whereRaw('id IN (' . $subquery . ')', [2, 2, 2])
    ->get();

我只想获取spotType属性等于“ Handicap”的位置。 我想得到以下输出结果:

'use strict';
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const spotSchema = new Schema({
    spotType: {
        type: String,
        enum: ['Normal','Handicap'],
        default: 'Normal'
    },
    used: {
        type: Boolean,
        default: false
    }
});

const streetSchema = new Schema({
    name: String,
    spots: [spotSchema]
})

const areaSchema = new Schema({
    description: String,
    streets: [streetSchema]
});

module.exports = mongoose.model('AreaModel', areaSchema);

或者如果很难获得上面的一个,那么这个波纹管就更简单了:

{
"_id": ObjectId("5c0ea6a64d8e4667682dd87e"),
"description": "Area A",
"streets": [{
        "_id": ObjectId("5c0ea6a64d8e4667682dd885"),
        "name": "streetA,
        "spots": [{
                "spotType": "Normal",
                "used": false,
                "_id": ObjectId("5c0ea6a64d8e4667682dd88a")
            },
            {
                "spotType": "Handicap",
                "used": false,
                "_id": ObjectId("5c0ea6a64d8e4667682dd889")
            }
        ]
    },
    {
        "_id": ObjectId("5c0ea6a64d8e4667682dd87f"),
        "nome": "streetB",
        "spots": [{
                "spotType": "Handicap",
                "used": false,
                "_id": ObjectId("5c0ea6a64d8e4667682dd882")
            },
            {
                "spotType": "Handicap",
                "used": false,
                "_id": ObjectId("5c0ea6a64d8e4667682dd881")
            },
            {
                "spotType": "Normal",
                "used": false,
                "_id": ObjectId("5c0ea6a64d8e4667682dd880")
            }
        ]
    }
],
"__v": 0
}

执行常规查询将向我返回所有子文档,即使那些子文档不符合我的搜索条件。

如果对Area模型进行查询,并使用该数据,我可以使用spotType =“ Handicap”来获得斑点,我可以使用reduce()来展平该结构,并且只有在以下情况下,我才能将数据推送到数组中spotType符合我的条件。

 [{
    "_id": ObjectId("5c0ea6a64d8e4667682dd885"),
    "name": "streetA",
    "spots": [{
        "spotType": "Handicap",
        "used": false,
        "_id": ObjectId("5c0ea6a64d8e4667682dd889")
    }]
},
{
    "_id": ObjectId("5c0ea6a64d8e4667682dd87f"),
    "nome": "streetB",
    "spots": [{
            "spotType": "Handicap",
            "used": false,
            "_id": ObjectId("5c0ea6a64d8e4667682dd882")
        },
        {
            "spotType": "Handicap",
            "used": false,
            "_id": ObjectId("5c0ea6a64d8e4667682dd881")
        }
    ]
}]

是否有一种更简单,更快速的方法来仅返回两个结果输出的Spots(SpotSchema)?

0 个答案:

没有答案