MongoDB query for distinct $type of a given field

With MongoDB's flexible schema, I'd like to learn the varying "$type" for a given field.

For example I can query to see all documents that meet the type I expect by

db.getCollection('sample').find({"_id": {$type: 7}})

How can I get a list of $type for sample._id ?

Or how can I re-write this query to show all documents that do not match the given type number?

Thanks!

Upvotes: 1

Views: 1473

Answers (2)

podolinsky.e
podolinsky.e

Reputation: 21

I was interested to get distinct value types of the certain field in the collection and the following request helps me

db.getCollection('<collection_name>').aggregate([
   { $project: { "fieldType": {  "$type": "$<field_name>"  } } } 
  ,{ $group : {_id: "$fieldType"} }
])

used links: Return actual type of a field in MongoDB

Upvotes: 2

klhr
klhr

Reputation: 3390

If you want to find all of the type for a given field, you'll want to use a mongo aggregation pipeline: https://docs.mongodb.com/manual/core/aggregation-pipeline/

If you want to rewrite this query to find all of the documents that are not of a certain type, you can use the $not operator -- https://docs.mongodb.com/manual/reference/operator/query/not/

{"_id": { $not: { $type: 7}}}

Not related to your question, but mongo 3.6 added aliases for types, so you could also write that query as {"_id": { $not: { $type: "objectId"}}} https://docs.mongodb.com/manual/reference/operator/query/type/

Upvotes: 0

Related Questions