Erik Olson
Erik Olson

Reputation: 6487

Find mongo docs with empty object in array

I have a Mongo collection with an array property, and the array has "empty" objects in it. What query can I use to target these non-empty arrays that have only {}?

I've tried combinations of $exists and $where to no avail.

Examples of data I need to target:

"arrayProperty" : [ {} ]

and

"arrayProperty" : [ {}, {} ]

EDIT:

Here's an example of the schema:

{
    "_id" : ObjectId("53b1ca583d597ce7cbd54646"),
    "arrayProperty" : [ 
        {
            "serialNumber" : "abc123",
            "rfid" : "xyz098",
            "size" : 95,
            "points" : 50,
            "frequency" : "Every day",
            "dateAssigned" : ISODate("2011-02-10T15:27:39.000Z")
        }
    ]
} 

Upvotes: 3

Views: 6547

Answers (2)

JohnnyHK
JohnnyHK

Reputation: 311835

If you're looking to find docs where arrayProperty contains at least one {} then it's just:

db.collection.find({ arrayProperty: {} })

If you're looking to find docs where arrayProperty only contains either one or two {}:

db.collection.find({ arrayProperty: {$in: [ [{}], [{}, {}] ] } })

Upvotes: 7

u3l
u3l

Reputation: 3412

The following may/may-not work...

db.collection.aggregate([
{$unwind: {"$arrayProperty"}},
{$match: {arrayProperty: {} }},
{$group: {_id: "$_id"} }
])

Basically what I'm trying to do is unwind arrayProperty, pull out all documents with an arrayProperty as {}, and group all of the unwinded documents back that have the same _id (or you can replace that with whatever unique key field you use).

Again, I don't know for sure if this will work so try it out and let me know.

Upvotes: 2

Related Questions