Checking array type before unwind

689 Views Asked by At

I have a document with the following structure

{testfields:[{"test_id":1,"test_name":"xxxx"}]},

but , my application don't no whether "testfield" is array or plain object, now if I apply "$unwind" in aggregate query and filed is not of array type "mongodb" throws error, that cannot unwind. I wanted to know is their a way I can check if the field is of type array than apply unwind, else treat is as normal object.

1

There are 1 best solutions below

2
On

I think this could help you.

Before using unwind, try to use a match to filter documents with testfields field is an array:

$match: { $where : "Array.isArray(this.testfields)" }

Then, you could use unwind without errors.