trycatch
trycatch

Reputation: 578

In a mongodb database, how do I find() and filter out any subdocuments?

If I have a mongodb database, is it possible to:

db.mydb.find(...)

Such that the result will filter out any subdocuments which may be present, without knowing what they are in advance?

For example, if I had:

{ "_id" : ObjectId("..."), "name" : "george", "address" : { "street" : "101 example way", "city" : "tutorial", "state" : "CA" }, "other thing" : "thing value" }

What arguments could I pass to find() that would result in getting:

{ "_id" : ObjectId("..."), "name" : "george", "other thing" : "thing value" }

without having to specify:

db.mydbl.find( {}, { "address" : 0} )

Does a method to suppress all subdocuments exist?

Upvotes: 1

Views: 225

Answers (1)

mickl
mickl

Reputation: 49945

If you want to dynamically remove any nested objects without specifying any existing keys, you can achieve that using aggregation framework:

db.col.aggregate([
    {
        $project: {
            keysAndValues: {
                $objectToArray: "$$ROOT"
            }
        }
    },
    {
        $addFields: {
            keysAndValues: {
              $filter: {
                 input: "$keysAndValues",
                 as: "kvPair",
                 cond: { $ne: [ { $type: "$$kvPair.v" }, "object" ] }
              }
            }
        }
    },
    {
        $replaceRoot: {
            newRoot: { $arrayToObject: "$keysAndValues" }
        }
    }
])

Basically the idea is quite simple: we want to transform a document into a list of key value pairs using ($objectToArray). Then we can filter out those key-value pairs where value is of $type "object". In last step we can transform our array back to an object using $arrayToObject

Upvotes: 1

Related Questions