数组最小值和最大值为$ lte $ gte

时间:2019-02-11 05:17:34

标签: mongodb mongodb-query aggregation-operators

我有一个数组,例如[3,4]。然后,我想搜索我的objectArray以查看数组中是否有任何数字与objectArray中的床位范围(从->到)相匹配。我的数组中只有一个数字需要匹配。

var objectArray = 
[
    {
        id: 1,
        customRange: {
            bed: {
                from: 2,
                to: 4
            }
        }
    },
    {
        id: 2,
        customRange: {
        bed: {
            from: 1,
            to: 5
        }
    }
    },
        {
            id: 3,
            customRange: {
            bed: {
                from: 1,
                to: 2
            }
        }
    }
];

由于性能我不想使用$ where。 有这样的东西吗? 假设params.beds = [3,4]

db.properties.find({
  $elemMatch: {
    "customRange.bed.from": {$gte: {$in: params.beds}},
    "customRange.bed.to": {$lte: {$in: params.beds}}
  }
})

3 个答案:

答案 0 :(得分:1)

您可以通过$expr

使用以下查询
SQSEndpoint:
    Type: AWS::EC2::VPCEndpoint
    Properties:
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          - Effect: Allow
            Principal: '*'
            Action:
              - 'sqs:*'
            Resource:
              - '*'
      ServiceName: !Join 
        - ''
        - - com.amazonaws.
          - !Ref 'AWS::Region'
          - .sqs
      SubnetIds:
        - !Ref PrivateSubnet
        - !Ref PublicSubnet
      VpcId: !Ref 'VPC'
      VpcEndpointType: Interface

答案 1 :(得分:0)

您可以使用 Filter Some

let data = [{ id: 1, customRange: {  bed: { from: 2,to: 4}}},{id: 2,customRange: { bed: { from: 1, to: 5 }}},{id: 3,customRange: { bed: { from: 1, to: 2 }}}]

let search = [3,4]

let op = data.filter(( {customRange: {bed: {from, to }}} ) => {
    return search.some(e => e >= from && e <= to)
  })
  
  console.log(op)

答案 2 :(得分:0)

一种解决方案是结合使用filter()find()来检查是否可以找到满足上述条件的物品:

const input = [
  {
    id: 1,
    customRange: {bed: {from: 2, to: 4}}
  },
  {
    id: 2,
    customRange: {bed: {from: 1, to: 5}}
  },
  {
    id: 3,
    customRange: {bed: {from: 1, to: 2}}
  }
];

let searchBeds = [3, 4];

let res = input.filter(
    ({customRange}) => searchBeds.find(
        x => (x >= customRange.bed.from) && (x <= customRange.bed.to)
    )
);

console.log(res);