How can I check if a field in MongoDB is [] or {}?
MongoDB. One of the fields of the document can be either an array, including an empty array, a subdocument, which can be empty or not, or null or does not exist at all. I need a find () condition that will match a non-empty nested document, and just 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 permission to change anything, I have to work with the database as it is. How do I state what find () is?
+3
source to share
2 answers
Use the following query:
db.test.find({
"fieldName": { "$gt": {} },
"fieldName.0": { "$exists": false }
})
For example, in 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
}
}
+3
source to share