2016-12-15 78 views
0

的內部陣列我有一個文件是這樣的:MongoDB的篩選對象

-document: users- 
{ 
"name": "x", password: "x" recipes: 
[{title: eggs, dificult: 1},{title: "pizza" dificult: 2}], 
name: "y", password: "y" recipes: [{title: "oil", dificult: 2},{title: "eggandpotatoes" dificult: 2}] 
} 

我想所有的食譜由標題和難治過濾

我已經嘗試了一些類似這樣的

db.users.find({$and: [{"recipes.title": /.*egg.*/},{"recipes.dificult": 2}]}, 
{"recipes.title": 1,"recipes.dificult": 1}).toArray(); 

這應該返回

{title: "eggandpotatoes" dificult: 2} 

但返回

{title: eggs, dificult: 1} 
{title: "eggandpotatoes" dificult: 2} 

我願再次過濾器的工作原理,限制與開始結果:2和端部:5 從2結果返回提前在未來5

感謝。

回答

1

可以使用$filter聚集篩選配方和$slice限制結果。它會給你所期望的一切,但正則表達式搜索這是不可能的。

db.users.aggregate([{ 
    $project: { 
     _id: 0, 
     recipes: { 
      $slice: [{ 
       $filter: { 
        input: "$recipes", 
        as: "recipe", 
        "cond": { 
         $and: [{ 
          $eq: ["$$recipe.title", "eggandpotatoes"] 
         }, { 
          $eq: ["$$recipe.dificult", 2] 
         }] 
        } 
       } 
      }, 2, 3] 
     } 
    } 
}]); 
0

如果你需要找出title正則表達式然後如下使用$elemMatch

db.users.find({"recipes":{"$elemMatch":{"title": /.*egg.*/,"dificult": 2}}}, {"recipes.$":1}) 

一件事,我在這裏提到的,如果你的recipes數組包含這樣

"recipes" : [ { "title" : "egg", "dificult" : 2 }, { "title" : "eggand", "dificult" : 2 } ]

一些事情

then $投影回報只有在上述情況下,第一個匹配陣列objcect這將是

"recipes" : [ { "title" : "egg", "dificult" : 2 } ]

如果需要此兩個數組,然後使用聚集

@Sagar答案