0

シナリオ: 「MyCollection」という名前のコレクション内の MongoDB に存在するドキュメントを検討してください。

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

私は知っておりUserID、それに基づいて取得したいと考えています。

問題: Node.js + MongoDB ネイティブ ドライバーで次のコードを試しました。

   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); 
                      });
           });

しかし、期待どおりに機能していません。

質問$match: MongoDBクエリ で演算子を使用して同じことを行う方法を知っている人はいますか?


更新:エラーは発生していません。しかし、オブジェクトは空白になります。[]

4

1 に答える 1

1

私はシェルで試しましたが、あなたの$match声明は間違っています - シェルで試しています

> 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
}

したがって、完全な集計は次のようになります。

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

$project(で投影するだけ_id$groupので、余分なものは必要ありませんが、_idユニークであるため、 を持って$projectを削除する必要があります$group

于 2013-04-16T12:38:12.627 に答える