Q:

MongoDB findby a column and count by other

I got a MongoDB collection with the following object structure,
{
    name: "hotel",
    products: [
       {
          id: 1,
          name: "flower"
       },
       {
          id: 350,
          name: "chocolate"
       }
    ]
}

Need to find all the objects that:
a) have the name "hotel" and 
b) the products number is bigger than 4. count($products)
I tried without success the following:
db.foo.find($and: [{name: "hotel"}, {products: {$gt: 4}}]);

A:

To find the number of elements in the products array, use a combination of the dot notation and $exists to look for the array index 4 (because array indexes in JavaScript are 0-based). If that index exists then it means your document has an array with size greater or equal to 5. Your final query should look like
var query = { "name": "hotel", "products.4": { "$exists": true } };
db.foo.find(query);

Another option is to use the $where operator:
var query = { "name": "hotel", "products" : { "$exists": true }, "$where": "this.products.length > 4"} )
db.foo.find(query);

Both queries tested with this sample data:
db.foo.insert([
{
    name: "hotel",
    products: [
       {
          id: 1,
          name: "flower"
       },
       {
          id: 350,
          name: "chocolate"
       }
    ]
},
{
    name: "hotel",
    products: [
       {
          id: 1,
          name: "flower"
       },
       {
          id: 350,
          name: "chocolate"
       },
       {
          id: 380,
          name: "candy"
       },
       {
          id: 390,
          name: "milk"
       },
       {
          id: 3,
          name: "newspaper"
       },
    ]
}
])

The queries above return the document:
{
    "_id" : ObjectId("551d6706180e849972938f8e"),
    "name" : "hotel",
    "products" : [ 
        {
            "id" : 1,
            "name" : "flower"
        }, 
        {
            "id" : 350,
            "name" : "chocolate"
        }, 
        {
            "id" : 380,
            "name" : "candy"
        }, 
        {
            "id" : 390,
            "name" : "milk"
        }, 
        {
            "id" : 3,
            "name" : "newspaper"
        }
    ]
}

