Query between a range of dates of a json in mongodb

0

I have the following collection in mongodb, I want to get the cveUsuario , activo and the historial , but the history only on days that are in the range of dates selected by the user.

{
  "_id": ObjectId("5847167aa7f950253039ef7e"),
  "cveUsuario": "000210",
  "activo": true,
  "historial": {
    "13 Jan 2017": {
      "VFVNTF03": [
        "09:38:33",
        "09:38:57",
        "09:39:38",
        "09:40:37"
      ],
      "CHPAGF099": [
        "16:38:41",
        "16:41:16"
      ]
    },
    "14 Jan 2017": {
      "CHRCAF003": [
        "09:33:21",
        "09:33:43"
      ],
      "CHPAGF099": [
        "10:36:22",
        "12:13:14"
      ]
    }
  },...
  {...}
}

I have the following query but when I use it in JAVA it does not bring me results, since if the user enters more than 4 days it gets bigger.

db.getCollection('sesiones').find({
    historial:{$exists:true},
    $or:[
        {"historial.24 Nov 2018":{$exists:true}},
        {"historial.23 Nov 2018":{$exists:true}},
        {"historial.22 Nov 2018":{$exists:true}}
    ]
},{
    cveUsuario:1,
    activo:1,
    "historial.24 Nov 2018":1,
    "historial.23 Nov 2018":1,
    "historial.22 Nov 2018":1
})

There is some way to simplify the query that I have, I am recent in the consultations with mongodb.

    
asked by JuankGlezz 27.11.2018 в 01:10
source

1 answer

3

You can make a $ where, and generate the search you want

db.sesiones.find({ 
    $where: function() { 
                dia = 24
                function exists(obj){
                    for (i = 0; i < 2; i++){
                        if (obj.hasOwnProperty('historial')){
                          if (obj.historial.hasOwnProperty('${dia +  i}Jan 2017')){
                                    return true;
                                } 
                        }
                        return false;    

                    }
                    return false;
                }
                return  exists(this)
        } 
    })
    
answered by 27.11.2018 / 19:19
source