I can see a few issues with this command:
db.location.aggregate([
{$match : { FirstName: { $nin : [" "] } } },
{$group: {_id : "$DeviceId" } },
{$project: { "DeviceId" : 1 } }
])
- The
$match stage will not match the document supplied in your question because the document you supplied has "FirstName" : " " so that document would be matched by $in but not by $nin
If the $match stage was changed to $in then it would emit a document and the grouping stage would have something to work on but the grouping stage is only configured to return an _id attribute so it returns the following intermediate document:
{
"_id" : "89984320001499681816"
}
The $project stage attempts to project "DeviceId" but the result of the grouping stage contains only an _id attribute so you cannot project a DeviceId attribute from that document.
By the time your aggregation pipeline reaches the forEach funciton there is no DeviceId, FirstName or LastName attribute in the documents.
To further understand what's happening inside the aggregation pipeline you could run this query:
db.location.aggregate([
{$match : { FirstName: { $in : [" "] } } },
{$project: { "DeviceId" : 1, FirstName: 1, LastName: 1 } }
]).forEach(
function(obj) {
print(obj);
}
);
Or, just run each stage in the pipeline on its own and review the output of each state since that becomes the input to the next stage. So, for example:
This command ...
db.location.aggregate([
{$match : { FirstName: { $in : [" "] } } }
])
... returns:
{
"_id" : ObjectId("59d13b64c26584cd8b7a15c8"),
"CreationDateTime" : ISODate("2017-09-26T06:39:29.105Z"),
"DeviceId" : "89984320001499681816",
"UserId" : UUID("bca0db12-2246-49a5-8703-b03fee45e50f"),
"FirstName" : " ",
"LastName" : ""
}
This command ...
db.location.aggregate([
{$match : { FirstName: { $in : [" "] } } },
{$group: {_id : "$DeviceId" } }
])
... returns:
{
"_id" : "89984320001499681816"
}
This command ...
db.location.aggregate([
{$match : { FirstName: { $in : [" "] } } },
{$group: {_id : "$DeviceId" } },
{$project: { "DeviceId" : 1 } }
])
... returns:
{
"_id" : "89984320001499681816"
}
This should make clear that once you add in the $group stage you lose the DeviceId, FirstName and LastName attributes hence they are not available for you to print in the forEach function.