1

limitwithおよびskipin phpを使用して、mongo ドキュメントの内部配列を取得します。

$db->users->findOne(array('_id' => new MongoId('5045fa0213cfcdfc06000008')));

上記のクエリは、mongo配列の下に表示されます

[_id] => MongoId Object (
    [$id] => 5045fa0213cfcdfc06000008
)
[items] => Array (
    [0] => 13
    [1] => 4
    [2] => 3
    [3] => 7
    [4] => 10
    [5] => 11
    [6] => 28
    [7] => 54
    [8] => 31
    [9] => 33
    [10] => 37
    [11] => 12
)

上記のmongo docで、以下のようなもの を利用することは可能ですlimitskip

$db->users->
  findOne(array('_id' => new MongoId('5045fa0213cfcdfc06000008')))->
    limit(5)->skip(5);

次のように出力されます

[_id] => MongoId Object (
    [$id] => 5045fa0213cfcdfc06000008
)
[items] => Array (
    [5] => 11
    [6] => 28
    [7] => 54
    [8] => 31
    [9] => 33
)

itemsそして、 mongoを使用して配列の総数を取得する方法は?

4

1 に答える 1

2

limit()およびメソッドはskip()、配列レベルではなく、ドキュメント レベルでのみ適用されます。

$slice演算子を使用して、配列のサブセットを取得できます。

$skip = 5;
$limit = 5;

$filter = array('_id' => new MongoId('5045fa0213cfcdfc06000008'));
$slice = array('items' => array( '$slice' => array( $skip, $limit ) ));

$db->users->findOne($filter, $slice);

現在 (MongoDB 2.2.0 のように) フェッチせずに配列のサイズを決定する簡単な方法はありません。新しいAggregation Frameworkを使用して何らかの操作を行うこともできますが、それはおそらくやり過ぎです。

一般的な使用パターンは$inc、アイテムが配列に追加または配列から削除されたときに、同じ更新でドキュメントのカウンターを調整するために使用することです。

そして、mongoを使用してアイテム配列の合計数を取得する方法は?

mongoシェルで Aggregation Framework を使用した簡単な例を次に示します。

db.users.aggregate(
    { $unwind: '$items' },
    { $group: {
        '_id': '$_id',
        itemcount: { $sum: 1 }
    }}
)
于 2012-10-08T07:10:17.340 に答える