How to use '$match' Aggregation Operators of MongoDB to match with the id of embedded document?

Scenario: Consider the document present in the MongoDB in collection named 'MyCollection'

       {
         "_id" : ObjectId("512bc95fe835e68f199c8686"),
         "author": "dave",
         "score" : 80,
         "USER" : {
                   "UserID": "Test1",
                   "UserName": "ABCD"
                  }
       },
       { "_id" : ObjectId("512bc962e835e68f199c8687"),
         "author" : "dave",
         "score" : 85,
         "USER" : {
                   "UserID": "Test2",
                   "UserName": "XYZ"
                  }
       },
       ...

I know the UserID and want to fetch based on that.

Issue: I tried the following code with Node.js + MongoDB-native driver:

   db.Collection('MyCollection', function (err, collection) {
        if (err) return console.error(err); 
        collection.aggregate([
                         { $match: { '$USER.UserID': 'Test2'} }, 
                        {$group: {
                            _id: '$_id' 
                        }
                    },
                        {
                            $project: {
                                _id: 1 
                            }
                        }
                      ], function (err, doc) {
                          if (err) return console.error(err);
                          console.dir(doc); 
                      });
           });

But its not working as expected.

Question: Can anyone know how to do the same with $match operator in MongoDB query?


Update: I am not getting any error. But the object will be blank i.e. []

I tried in the shell and your $match statement is wrong - trying in the shell

> db.MyCollection.find()
{ "_id" : ObjectId("512bc95fe835e68f199c8686"), "author" : "dave", "score" : 80, "USER" : { "UserID" : "Test1", "UserName" : "ABCD" } }
{ "_id" : ObjectId("512bc962e835e68f199c8687"), "author" : "dave", "score" : 85, "USER" : { "UserID" : "Test2", "UserName" : "XYZ" } }
> db.MyCollection.aggregate([{$match: {"$USER.UserID": "Test2"}}])
{ "result" : [ ], "ok" : 1 }
> db.MyCollection.aggregate([{$match: {"USER.UserID": "Test2"}}])
{
    "result" : [
        {
            "_id" : ObjectId("512bc962e835e68f199c8687"),
            "author" : "dave",
            "score" : 85,
            "USER" : {
                "UserID" : "Test2",
                "UserName" : "XYZ"
            }
        }
    ],
    "ok" : 1
}

So the full aggregation would be:

db.MyCollection.aggregate([
  {$match: {"USER.UserID": "Test2"}},
  {$group: {"_id": "$_id"}},
  {$project: {"_id": 1}}
])

(You don't need the extra $project as you only project _id in the $group but equally as _id is unique you should just have the $project and remove the $group)