4

MongoDB. One of the fields of a document can be either an array, including an empty array, a subdocument, that can be empty or not, or null, or not exist at all. I need a condition for find() that will match a non-empty subdocument, and only that.

So:

fieldName: {} - no match.
fieldName: [ { id:0 } ] - no match.
fieldName: [ {} ] - no match.
No field called fieldName - no match.
fieldName: null - no match.
fieldName: { id: 0 } - match.

I have no rights to modify anything, I have to work with the database as is. How to formulate that find() ?

Community
  • 1
  • 1
user2649762
  • 541
  • 3
  • 13
  • possible duplicate of [In MongoDB, how do I find documents where array size is greater than 1?](http://stackoverflow.com/questions/7811163/in-mongodb-how-do-i-find-documents-where-array-size-is-greater-than-1) – Neo-coder Jun 03 '15 at 10:29
  • Can you describe it a bit more clearly? Do I get it right that there is a semantic difference wether the same key holds an array or a subdocument? – Markus W Mahlberg Jun 04 '15 at 08:25

2 Answers2

3

Use the following query:

db.test.find({ 
   "fieldName": { "$gt": {} }, 
   "fieldName.0": { "$exists": false } 
})

For example, with the above test case, insert the following documents:

db.test.insert([
    { _id: 1, fieldName: {} },
    { _id: 2, fieldName: [ { id: 0 } ] },
    { _id: 3, fieldName: [ {} ] },
    { _id: 4 },
    { _id: 5, fieldName: null},
    { _id: 6, fieldName: { id: 0 } }
])

the above query will return the document with _id: 6

/* 0 */
{
    "_id" : 6,
    "fieldName" : {
        "id" : 0
    }
}
chridam
  • 100,957
  • 23
  • 236
  • 235
1

You can use the $type and the $exists operator.

The first check the type of id and the latter if fieldname is an array using the so called dot notation.

db.collection.find({ 
    "fieldName.id": { $type: 1 }, "fieldName.0": { $exists: false }
})
styvane
  • 59,869
  • 19
  • 150
  • 156