Query documents to filter out ObjectId

Dear all,
I have a collection where one field should be an ObjectId. However, for some documents, that field appears as a string. Is there a way to filter out the documents where the field is an ObjectId, so I only can see the cases where they are strings?

Thank you in advance.

Hello @Cesar_Beleno, welcome to the MongoDB Community forum!

You can use the $type query operator to check if a field is of a specific type.

The following query will match the field id and returns documents where the values are of type ObjectId:

db.collection.find( { id: { $type: 'objectId' } )

To match documents with the field id's data type is a string:

db.collection.find( { id: { $type: 'string' } )

The second query is what you are looking for!

2 Likes

Dear @Prasad_Saya, thank you very much for your tip, that helped me a lot!!

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.