select array part

71 views
Skip to first unread message

Jane

unread,
Oct 17, 2012, 11:37:46 AM10/17/12
to mongod...@googlegroups.com

Hi,

we need to store array in one document and select part of array that matches criteria, for example some field value flag =1

doc1 : {   

           somefileld:"somevalue"

          array: [ {id :1, flag:1}, {id :2, flag:2}      }, {id :3, flag:1}      ]

}

result will be:

 

doc1 : {   

           somefileld:"somevalue"

          array: [ {id :1, flag:1}, {id :3, flag:1}          ]

}

 

Is it possible?

Stephen Lee

unread,
Oct 17, 2012, 11:48:18 AM10/17/12
to mongod...@googlegroups.com
I don't think you can select specific indexes of an array, but you can slice ranges of a document's array field.

Kevin Henry

unread,
Oct 17, 2012, 12:00:41 PM10/17/12
to mongod...@googlegroups.com
Look into $elemMatch in conjunction with getting the array element by
position. I'm not sure if it will get you what you want but may be
close enough.

http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24elemMatch

http://www.mongodb.org/display/DOCS/Dot+Notation+%28Reaching+into+Objects%29#DotNotation%28ReachingintoObjects%29-ArrayElementbyPosition


Kevin



Kevin Henry
knrh...@gmail.com
> --
> You received this message because you are subscribed to the Google
> Groups "mongodb-user" group.
> To post to this group, send email to mongod...@googlegroups.com
> To unsubscribe from this group, send email to
> mongodb-user...@googlegroups.com
> See also the IRC channel -- freenode.net#mongodb

Stephen Lee

unread,
Oct 17, 2012, 12:52:17 PM10/17/12
to mongod...@googlegroups.com
You can almost accomplish this using the Aggregation Framework, specifically a pipeline of $unwind and $match.

Eg.

db.collection.aggregate(
    {$unwind:"$array"},  // this multiplexes each document by array element
    {$match:{"array.flag":1}}
);

Unfortunately, there isn't a "$wind" operator.  You'll be left with the array elements spread across duplicate documents, but then, your client code could accumulate into a single document with single array field.

Jane

unread,
Oct 18, 2012, 4:53:50 AM10/18/12
to mongod...@googlegroups.com
Thank you very much. Can aggregation framework make slower query?

среда, 17 октября 2012 г., 20:52:17 UTC+4 пользователь Stephen Lee написал:

Stephen Lee

unread,
Oct 18, 2012, 9:42:31 AM10/18/12
to mongod...@googlegroups.com
I can't definitively whether it will be slower, but it can seem slower if you don't plan your aggregation framework properly.  It's advised that you do a $match upfront so you limit the records that the rest of the aggregation pipeline has to operate upon.  $match should use the same query mechanism that regular .find().  After the $match, everything else is done in memory, and at minimum, it should be faster than doing Map/Reduce.
Reply all
Reply to author
Forward
0 new messages