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?

1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.