在嵌套数组中查找匹配条件的第一个元素 [英] Find first element in nested array that match conditions

查看:207
本文介绍了在嵌套数组中查找匹配条件的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下文件:

doc1: { 
  'array': [
    {'field': 'ABC', 'enabled': 'false'},
    {'field': 'BCD', 'enabled': 'true'},
    {'field': 'DEF', 'enabled': 'false'},
    {'field': 'XYZ', 'enabled': 'true'},
  ]
}


doc2: { 
  'array': [
    {'field': 'ABC', 'enabled': 'true'},
    {'field': 'BCD', 'enabled': 'true'},
    {'field': 'DEF', 'enabled': 'false'},
    {'field': 'XYZ', 'enabled': 'true'},
  ]
}

我正在按特定领域进行搜索. 我想获取所有启用了此字段的文档,并且在此之前(列表中)没有启用其他字段.

I'm performing search by particular field. I want to get all documents that have this field enabled, and there are no other fields enabled before this (in the list).

例如:

搜索字段:BCD,已启用:true-应该仅返回第一个文档(因为第二个文档ABC也已启用).

search for field: BCD, enabled: true - should return only first document (because in second document ABC is enabled too).

搜索XYZ,已启用:true-完全不应该返回任何文档,因为此列表顶部还启用了其他字段.

search for XYZ, enabled: true - should not return any documents at all, because there are other fields enabled on top of this list.

我试图对$elemMatch做某事,但是我不知道是否有可能在elemMatch匹配的元素之上应用过滤器.

I was trying to do smth with $elemMatch, but I don't know if it's possible to apply filter on top of element that elemMatch has matched.

有什么建议吗?

推荐答案

$where关键字允许出于类似目的生成复杂的条件.

There is $where keyword that allow to generate complex conditions for similar purpose.

find($where: 'this.array.filter(function(e){return e.enabled=="true"})[0].field=="ABC"')

由于它不使用任何索引,因此我将添加更多条件以从优化中受益.

As this does not use any indexes, I'll add more conditions to benefit from optimisation.

这篇关于在嵌套数组中查找匹配条件的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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