In my mongoDB collection, the data structure includes:
{
"_id" : ObjectId("..."),
"records" : [
ISODate("2020-04-19T00:49:18.945Z"),
{
"_id" : ObjectId(""),
"date" : ISODate("2020-05-07T04:49:55.643Z"),
"text" : "someText"
}
],
}
Due to version upgrades, the content in records
varies.
I am looking to aggregate records.text
from all documents while disregarding any missing data. I attempted to use code shared on MongoDB: Aggregate and flatten an array field
db.collection.aggregate({$unwind : "records"},
{$project: {_id: 1, 'text': '$records.text'}})
However, this resulted in the following error message:
The path option to $unwind stage should be prefixed with a '$': records
I then tried to rectify the error based on instructions provided in these directions, aiming to handle empty fields:
db.collection.aggregate({$unwind : "records", includeEmpty: false},
{$project: {_id: 1, 'text': '$records.text'}})
Yet,d this resulted in another error:
A pipeline stage specification object must contain exactly one field.
How can I effectively aggregate values from nested arrays that may have empty elements?