T. Ato
T. Ato

Reputation: 143

MongoDB Query for Array Index in Embedded Document

I'm trying to query a specific array index in a document that looks like this:

"_id" : ObjectId("5756ea5a59985a9eb714d50b"),
    "fs" : "is",
    "values" : {
            "l_25" : [
                    0,
                    0,
                    0,
                    0,
                    0,
                    NumberLong("2332000000"),
                    NumberLong("2166000000"),
                    NumberLong("2517000000"),
                    NumberLong("2664000000"),
                    NumberLong("2853000000"),
                    NumberLong("2866000000")
            ],
            "l_24" : [
                    0,
                    0,
                    0,
                    0,
                    0,
                    2030000000,
                    2006000000,
                    NumberLong("2420000000"),
                    NumberLong("2614000000"),
                    NumberLong("2803000000"),
                    NumberLong("2817750000")
            ],
    "updated" : ISODate("2016-06-07T15:38:01.898Z"),
    "v" : 1

Querying for l_25 (e.g., p.find({'fs' : 'is'},{'values.l_25' : 1})) returns the array just fine. But trying to query a specific index in the array (p.find({'fs' : 'is'},{'values.l_25.6' : 1})) returns l_25 with empty brackets. How do I query the specific index without knowing the value of its inhabitant?

Upvotes: 0

Views: 92

Answers (1)

profesor79
profesor79

Reputation: 9473

you can get this by using $slice in projection

db.ato.find( {}, { "values.l_25": { $slice: [ 5, 1 ] } } )

this will skip 5 elements and take one

output:

{
    "_id" : ObjectId("5756ea5a59985a9eb714d50b"),
    "fs" : "is",
    "values" : {
        "l_25" : [ 
            NumberLong(2332000000)
        ],
        "l_24" : [ 
            0.0, 
            0.0, 
            0.0, 
            0.0, 
            0.0, 
            2030000000.0, 
            2006000000.0, 
            NumberLong(2420000000), 
            NumberLong(2614000000), 
            NumberLong(2803000000), 
            NumberLong(2817750000)
        ],
        "updated" : ISODate("2016-06-07T15:38:01.898Z"),
        "v" : 1.0
    }
}

Upvotes: 1

Related Questions