понедельник, 23 августа 2010 г.

MongoDB. How to filter embedded array items of document.

Let we have collection

> db.A.find(); 

{ "_id" : ObjectId("4c70b753d87f000000006850"), "Name" : "Doc1", 
"Items" : [ 
        {                "x" : 1,                "y" : 1        }, 
        {                "x" : 1,                "y" : 2        }, 
        {                "x" : 3,                "y" : 3        }] } 
{ "_id" : ObjectId("4c70b888d87f000000006851"), "Name" : "Doc2", 
"Items" : [ 
        {                "x" : 3,                "y" : 1        }, 
        {                "x" : 2,                "y" : 1        }, 
        {                "x" : 1,                "y" : 3        }] } 

Let say we want to get items where A.Items.x>1.

we use server-stored function for this purposes.

var x = function() {
    var docs = db.A.find();                 // condition 1 to find. get cursor
    var d = null, i = null, ret = [];
    while (docs.hasNext())                    // get items one by one
    {
        d = docs.next().Items;                 // access embedded array here
        if (d == null) continue;
        for (var i = 0; i < d.length; i++)    // step one by one
            if (d[i].x > 1)                    // condition 2 . filter by content here
                ret.push(d[i]);                // push to output if need.
    }
    return ret;
};

And have the following output

> x()
[
        {
                "x" : 3,
                "y" : 3
        },
        {
                "x" : 3,
                "y" : 1
        },
        {
                "x" : 2,
                "y" : 1
        }
]

0 коммент.:

Отправить комментарий