猫鼬-基于枚举值的聚合$ match [英] Mongoose - Aggregation $match based on enum values

查看:75
本文介绍了猫鼬-基于枚举值的聚合$ match的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与猫鼬聚合,我得到的对象看起来像这样:

I have an aggregation with mongoose, the objects what i get looks like this:

foods: {
  fruits: {
    apple: 'NONE',
    banana: null,
    pearl: 'INCLUDED'
  }
}

水果可以有4个值:null,'NONE','INCLUDED','EXTRA'

The fruits can have 4 values: null, 'NONE', 'INCLUDED', 'EXTRA'

我的目标是在此聚合中创建$ match/filter,以便能够过滤出null和'NONE'值.

My goal is to make the $match/filter in this aggregation, to be able to filter out the null and 'NONE' values.

是否可以选择执行此操作?

Is there any option to do this?

就像聚合一样,我有这个:

Like at the aggregation i have this:

    {
        $match: 'foods.fruits.pearl',
    }

然后取回那些珍珠具有'INCLUDED'或'EXTRA'值的物体吗?

Then get back those objects where the pearl have 'INCLUDED' or 'EXTRA' value?

推荐答案

您可以在mongodb 3.4.4 及更高版本

You can try below aggregation in mongodb 3.4.4 and above

好吧,您这里的未知键具有NONEnull的值,因此,您可以使用

Well you have unknown keys here having value with NONE and null and therefore, you can use $objectToArray aggregation to make keys into values and can easily $match with them

db.collection.aggregate([
  { "$addFields": {
    "data": { "$objectToArray": "$foods.fruits" }
  }},
  { "$match": { "data.v": { "$in": [ "NONE", null ] } } },
  { "$project": { "data": 0 }}
])

这篇关于猫鼬-基于枚举值的聚合$ match的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆