Search code examples
node.jsmongodbmongodb-querymongoskin

How to put an array with or between items in mongodb projection query?


I have a mongodb database which stores items in the following format:

{
"2013" : {
    "2" : {
        "1" : {
            "item1" : {
                "1" : {
                    "a_type" : 10,
                    "b_type" : 5,
                }
            },
            "item2" : {
                "v1" : {
                    "a_type" : 10,
                    "b_type" : 5,
                }
            },
        },
        "3" : {
            "item1" : {
                "1" : {
                    "a_type" : 10,
                    "b_type" : 5
                },
                "3" : {
                    "a_type" : 10,
                    "b_type" : 5
                }
            },
            "item2" : {
                "v1" : {
                    "a_type" : 10,
                    "b_type" : 5
                }
            },
        }
    }
}
"2014" : {
    "1" : {
        "5" : {
            "item1" : {
                "1" : {
                    "a_type" : 10,
                    "b_type" : 5
                }
            },
            "item2" : {
                "v2" : {
                    "a_type" : 10,
                    "b_type" : 5
                }
            },
        },     
    },
}
"_id" : ObjectId("53b82417a4b4939c27e300ed")
}

I want to get some specific item data in a specific date with my query. I can do it for one day or more with hard coding but I want to give it an array which will be filled automatically with the specific dates and item names but after more than one day of searching in stack and mongo docs I couldn't find anything. Please help me with this. Query for getting one specific item and date is like this :

db.collection(collectionName).findOne({}, {'2013.2.1.item1': 1, '2014.1.5.item2': 1},  function(err, res});

Thanks


Solution

  • Imagine your array which contains your query items is:

     var query = ['2013.2.1', '2014.1.5'];
    

    Because of your DB structure, you have to use MongoDB projection to extract the query items, so you should do something like this

    var projectionObj = {};
    for(var item in query) {
        projectionObj[item] = 1;
    }
    

    It will produce bellow object:

    {
        '2013.2.1': 1,
        '2014.1.5': 1
    }
    

    Then you can pass it to MongoDB find function like this:

    db.collection([collectionName]).find({}, projectionObj);
    

    It will return exactly what you want.