Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongo DB: how to select items with nested array count > 0

The database is near 5GB. I have documents like:

{
    _id: ..
    user: "a"
    hobbies: [{
        _id: ..
        name: football
    },
    {
        _id: ..
        name: beer
    }
    ...
    ]
}

I want to return users who have more then 0 "hobbies" I've tried

db.collection.find({"hobbies" : { &gt : 0}}).limit(10)

and it takes all RAM and no result.

  1. How to do conduct this select?
  2. And how to return only: id, name, count ?
  3. How to do it with c# official driver?

TIA

P.S. near i've found: "Add new field to hande category size. It's a usual practice in mongo world." is this true?

like image 390
1gn1ter Avatar asked Sep 26 '11 07:09

1gn1ter


3 Answers

In this specific case, you can use list indexing to solve your problem:

db.collection.find({"hobbies.0" : {$exists : true}}).limit(10)

This just makes sure a 0th element exists. You can do the same to make sure the list is shorter than n or between x and y in length by checking the existing of elements at the ends of the range.

like image 199
Parker Avatar answered Oct 02 '22 17:10

Parker


Have you tried using hobbies.length. i haven't tested this, but i believe this is the right way to query the range of the array in mongodb

db.collection.find({$where: '(this.hobbies.length > 0)'})
like image 37
RameshVel Avatar answered Oct 02 '22 18:10

RameshVel


You can (sort of) check for a range of array lengths with the $size operator using a logical $not:

db.collection.find({array: {$not: {$size: 0}}})
like image 23
jayelm Avatar answered Oct 02 '22 18:10

jayelm