2

I have a document which looks like this:

{
  "_id" : ObjectId("50a8240b927d5d8b5891743c"),
  "cust_id" : "abc",
  "ord_date" : ISODate("2012-10-03T18:30:00Z"),
  "status" : "A",
  "price" : 25,
  "items" : [
    {
      "sku" : "mmm",
      "qty" : 5,
      "price" : 2.5
    },
    {
      "sku" : "nnn",
      "qty" : 5,
      "price" : 2.5
    }]
}

now I want to query using $where for all items whose "qty">5 and "sku"=='mmm',

I tried the following
{
   "$where" : "this.items.some(function(entry){return entry.qty>5})&&this.items.some(function(entry){return entry.sku=='ggg'})
}

but it dosen't work. I want to do it only by using "$where"

Chris Heald
  • 61,439
  • 10
  • 123
  • 137
Phalguni Mukherjee
  • 623
  • 3
  • 11
  • 29

1 Answers1

1

Using $where you can create a for loop with an if where you will set the conditions. It will return true if the conditions are satisfied:

db.col_t.find(
   { 
      $where: "for (var i = 0; i < this.items.length; ++i) { if (this.items[i].sku === 'mmm' && this.items[i].qty > 5) return true; }"
   }).pretty();

Or shorter putting the value of $where directly, like bellow:

db.col_t.find("for (var i = 0; i < this.items.length; ++i) { if (this.items[i].sku === 'mmm' && this.items[i].qty > 5) return true; }").pretty();

I recommend you to use $elemMatch and $gt this way:

Query:

{
   items: {
     $elemMatch: {
        qty: { $gt: 5 },
        sku: "mmm"
     }
   }
}

Warning: This query will not retrieve your document because using $gt it will search for numbers bigger (>) than 5. Use $gte if you want >=.


References:

$elemMatch

The $elemMatch operator matches more than one component within an array element

read more

$gte

Syntax: {field: {$gte: value} }

$gte selects the documents where the value of the field is greater than or equal to (i.e. >=) a specified value (e.g. value.)

read more

$gt

Syntax: {field: {$gt: value} }

$gt selects those documents where the value of the field is greater than (i.e. >) the specified value.

read more

Community
  • 1
  • 1
Ionică Bizău
  • 109,027
  • 88
  • 289
  • 474