1

I have documents that look like this (for example purposes).

{
    "_id" : ObjectId("591675e89a89201e4d520c89"),
    "raw_data_history" : {
        "APR-2017" : [ 
            {
                "count" : "540421",
                "reason" : "blah blah",
            },
            {
                "count" : "111111",
                "reason" : "blah blah 2",
            }
        ],
 "MAY-2017" : [ 
            {
                "count" : "13",
                "reason" : "blah blah",
            },
            {
                "count" : "100",
                "reason" : "blah blah 2",
            }
        ],
    },
    "review" : false,
    "active" : true,

}

I want to get all the documents in the collection where APR-2017 has more than 1 array element contents. I have tried the following:

db.getCollection('collections').find( {raw_data_history.APR-2017 : {$exists:true}, $where:'this.raw_data_history.APR-2017.length>1'} )

but I get

Error: Line 1: Unexpected token .

How can I do that?

kratos
  • 2,465
  • 2
  • 27
  • 45
  • Possible duplicate of [Query for documents where array size is greater than 1](http://stackoverflow.com/questions/7811163/query-for-documents-where-array-size-is-greater-than-1) – s7vr May 13 '17 at 12:16

2 Answers2

1

Use to $size operator in aggregation. If you want to do it without aggregating, you'll need to have a field to store the size of your array. $size documentation

db.collections.aggregate( {$project : {numberOfElements : {$size : "$raw_data_history.APR-2017"}, doc : "$$ROOT"}}, {$match : {numberOfElements : {$gt : 1}}} )

Edit : A little clarification:

  • $project stage will project the size of your array, along with the full document. It's practically like adding a field to keep track of the array size to your document.
  • $match stage simply filters the document, so that it'll only return you document with more than 1 array in APR-2017
Tan Kim Loong
  • 980
  • 7
  • 14
1

When you want to use field inside object, you have to pass that field name in quotes("").

below query work for your requirement.

db.getCollection('collections').find( {"raw_data_history.APR-2017.1" : {$exists:true}} )

put raw_data_history.APR-2017.1 in double quotes.