4

次の MongoDB ドキュメントがあります。

{
 _id: ObjectId(5), 
 items: [1,2,3,45,4,67,9,4]
}

フィルタされたアイテム (1、9、4) を含むドキュメントを取得する必要があります

結果:

{
 _id: ObjectId(5), 
 items: [1,9,4]
}

$elemMatch プロジェクションを試しましたが、1 つのアイテムしか返されません。

A.findById(ObjectId(5))
   .select({ items: { $elemMatch: {$in: [1, 9, 4]}}})
   .exec(function (err, docs) {
      console.log(doc); // { _id: ObjectId(5), items: [ 1 ] }
      done(err);
});

項目が 1、9、4 のみのドキュメントを取得するにはどうすればよいですか?

4

3 に答える 3

4

A.items = A.items.filter( function(i) {return i == 1 || i == 9 || i == 4} );

于 2012-09-26T03:07:05.670 に答える
3

MongoDB (3.2+) の最新バージョンでは、$filter演算子を使用して、指定された条件に基づいて返す配列フィールドのサブセットを選択できます。返される要素は、フィールド配列からの元の順序になります。

mongoシェルでの例:

db.items.aggregate([
    { $match : {
        _id: 5
    }},
    { $project: {
        items: {
            $filter: {
                input: "$items",
                cond: {
                    "$in": ["$$this", [1, 9, 4]]
                }
            }
        }
     }
}])

注: この質問の元の配列には値が42 回あるため、$filterコマンドは両方の出現を返します。

{ "_id" : 5, "items" : [ 1, 4, 9, 4 ] }

一意の一致するアイテムのみを返す代替アプローチの場合、$setIntersection演算子を使用できます。

db.items.aggregate([
    { $match : {
        _id: 5
    }},        
    { $project: {
        items: {
            $setIntersection: ['$items', [1,4,9]] 
        }
    }}
])

これは以下を返します: { "_id" : 5, "items" : [ 1, 4, 9 ] }.

(2012 年 9 月の元の回答を以下に示します)

ドキュメント操作をサーバー側で行いたい場合は、MongoDB 2.2のAggregation Frameworkを使用できます。

db.items.aggregate(

  // Match the document(s) of interest
  { $match : {
     _id: 5
  }},

  // Separate the items array into a stream of documents
  { $unwind : "$items" },

  // Filter the array
  { $match : {
    items: { $in: [1, 9, 4] }
  }},

  // Group the results back into a result document
  { $group : {
     _id: "$_id",
     items: { $addToSet : "$items" }
  }}
)

結果:

{
    "result" : [
        {
            "_id" : 5,
            "items" : [
                9,
                4,
                1
            ]
        }
    ],
    "ok" : 1
}
于 2012-09-26T03:51:02.110 に答える
0

node.js アプリでアンダースコアを使用します。

npm install underscore

var _ = require('underscore');

配列の交差関数を使用できます。

 intersection_.intersection(*arrays)

すべての配列の共通部分である値のリストを計算します。結果の各値は、各配列に存在します。

_.intersection([1, 2, 3], [101, 2, 1, 10], [2, 1]);
=> [1, 2]

http://documentcloud.github.com/underscore/#intersection

于 2012-09-26T04:17:02.593 に答える