Question on query

40 views
Skip to first unread message

resting

unread,
May 24, 2013, 4:52:06 AM5/24/13
to mongod...@googlegroups.com

Given that I have many documents of the following structure:

{
  "_id" : ObjectId("519c643bc76110cb6e794782"),
  "item" : "1",
  "packets" : { 
    "0" : "0",
    "1" : "0",
     "2" : "1",
    ...
  }
}

How do I query for all documents with packets > 3 (irregardless of key value) for example?

Thanks.

Tyler Brock

unread,
May 24, 2013, 8:06:37 AM5/24/13
to mongod...@googlegroups.com
Create a field that keeps a count of the number of packets.

Then query for { packets_size: { $gt: 3 } }

-Tyler

Rob Moore

unread,
May 24, 2013, 3:39:30 PM5/24/13
to mongod...@googlegroups.com

How do I query for all documents with packets > 3 (irregardless of key value) for example?


If you can't or don't want to maintain a separate field then you can also use something like:

  db.collection.find( { "packets.3" : { "$exists" : true } } )

This assumes that all of the elements in the "packets" document are sequentially numbered and have no gaps... 

This trick would also work if "packets" was an array.

Rob.

resting

unread,
May 29, 2013, 1:25:04 AM5/29/13
to mongod...@googlegroups.com
Hi Tyler,

I wasn't clear previously, here's the structure of the packets again with explanation

"packets" : {
   "0" : "0",
   "1" : "0",
    "2" : "1",
   ...
}

"0" : "0" means at interval 0, there are 0 packets  
"2" : "1" means at interval 2, there was 1 packet
So the key is the interval, and value is already the packet size. 

The objective is to locate the document (so I know which item it belongs to), with a packet size that was greater than x (any integer value), irregardless of which interval it was.

Thanks.

Rob Moore

unread,
May 29, 2013, 2:03:13 PM5/29/13
to mongod...@googlegroups.com

Ah! Looking at the wrong side of the tuples.

Are all of the intervals always filled in for the range [0, N] for some N?  If so then (its ugly but) you can enumerate all of the fields in the query within an $or.  For N = 4:

    db.collection.find( { $or : [ 'packets.0' : { '$gt' : 3 },  'packets.1' : { '$gt' : 3 },  'packets.2' : { '$gt' : 3 }, 'packets.3' : { '$gt' : 3 }, 'packets.4' : { '$gt' : 3 } ] } )

Have you considered changing 'packets' to an array of integers where  the position is the interval and the value is the number of packets? e.g.,

"packets" : [
   0,
   0,
   1,
   ...
]

If you did that then a query like this would work:

   db.collection.find( { 'packets' : { '$gt'  : 3 } } )

Rob.
Reply all
Reply to author
Forward
0 new messages