1
{
   "name": "comments",
   "rid": 456,

   "refs": [
     {
       "no": 1,
       "info": "this is first"  
    },
     {
       "no": 2,
       "info": "this is second" 
    },
     {
       "no": 3,
       "info": "this is third"  
    } 
  ] 
}
{
   "name": "comments",
   "rid": 321,

   "refs": [
     {
       "no": 1,
       "info": "this is first-h"  
    },
     {
       "no": 2,
       "info": "this is second-h" 
    },
     {
       "no": 3,
       "info": "this is third-h"  
    } 
  ] 
}

上記のようなドキュメント構造があるとします。rid が 456 で、no が 2 の配列を取得する必要があります。したがって、配列を取得したいだけです。

     {
       "no": 2,
       "info": "this is second" 
    }

どうすればそれができますか?

4

2 に答える 2

3

JohnnyHK の位置演算子の使用に加えて、MongoDB 2.2+ でこれにアプローチする方法がいくつかあります。

アプローチ #1:$elemMatchプロジェクションを使用する

$elemMatch射影は、配列の単一の一致する要素を含めるために使用できます。デフォルトでは、結果には document も含まれ_idますが、必要ない場合はこれを除外できます。

db.comments.find(
    { rid: 456 },
    { _id:0, refs: { $elemMatch: { no: 2 } }}
)

出力例:

{ "refs" : [ { "no" : 2, "info" : "this is second" } ] }

アプローチ #2: 集約フレームワークを使用する

Aggregation Framework$unwindには、配列と$matchドキュメント基準に対する演算子が含まれています。$elemMatchこのアプローチは、配列ごとに複数の一致を返すことができるため、射影を使用するよりも柔軟性があります。

db.comments.aggregate(

    // Find matching documents of interest (can use an index)
    { $match: { rid: 456 }},

    // Create stream of documents based on the `refs` array
    { $unwind: "$refs" },

    // Match the specific refs element(s) of interest
    { $match: { "refs.no" : 2 }},

    // Project the desired output
    { $project: {
        _id: 0,
        no: "$refs.no",
        info: "$refs.info"
    }}
)

出力例:

{
    "result" : [
        {
            "no" : 2,
            "info" : "this is second"
        }
    ],
    "ok" : 1
}
于 2013-01-06T04:31:10.617 に答える
1

ドット表記を使用して目的のドキュメントを検索し、$位置演算子を使用して一致した配列要素だけを結果に含めることができます。

 db.test.find({rid: 456, 'refs.no': 2}, {_id: 0, 'refs.$': 1})

戻り値:

{ "refs": [ { "no": 2, "info": "this is second" } ] }
于 2013-01-06T04:22:50.830 に答える