2017-02-21 115 views
0

我有一個數組元素,同時使用$ elemmatch從$ mongo中選擇數據,然後返回條件不匹配的所有元素。如何刪除mongodb中條件不匹配的記錄

db.user.find({$and: [{ 
    roles: { $all: [ 
     { "$elemMatch" : {$or:[{ effectiveTo: { $gt: new Date()} } , { effectiveTo: null }]}} 
    ]} 
}, 
{ 
    groups: { $all: [ 
     { "$elemMatch" : {$or:[{ effectiveTo: { $gt: new Date()} } , { effectiveTo: null }]}} 
    ]} 
}]}) 
+0

而不是找到使用刪除。檢查這個鏈接https://docs.mongodb.com/manual/reference/method/db.collection.remove/ –

+0

這上面的查詢返回groups數組的所有元素,其中effectiveTo日期不大於當前日期,那些我想刪除.. –

+0

@MohitJain,謝謝,但我不想刪除我的數組元素,只需要獲取顯示在門戶網站...需要保持所有記錄.. –

回答

0

你想要做什麼,基本上過濾MongoDB中的子陣列。 周圍有很多similar questions

你不能這樣做.find()但你可以通過聚合來實現。

最簡單的方法是使用$過濾

在你的情況,請試試這個(可從MongoDB的v啓動3.2):

var currentDate = new Date(); 
 
var effectiveToCondition = { 
 
    $elemMatch: { 
 
     $or: [ 
 
      {effectiveTo: {$gt: currentDate}}, 
 
      {effectiveTo: null} 
 
     ] 
 
    } 
 
}; 
 
db.user.aggregate([ 
 
{ 
 
    $match: { 
 
     $and: [ 
 
      { 
 
       $or: [ 
 
        {roles: {$size: 0}}, 
 
        {roles: effectiveToCondition} 
 
       ] 
 
      }, 
 
      { 
 
       $or: [ 
 
        {groups: {$size: 0}}, 
 
        {groups: effectiveToCondition} 
 
       ] 
 
      } 
 
     ] 
 
    } 
 
}, 
 
//Will filter out the records where groups AND rolse are both empty 
 
//Please uncomment if needed 
 
// { 
 
// $match: { 
 
//  $or: [ 
 
//   {'groups.0': {$exists: true}}, 
 
//   {'roles.0': {$exists: true}} 
 
//  ] 
 
// } 
 
// }, 
 
{ 
 
    $project: { 
 
     user: '$$ROOT', 
 
     filteredRoles: { 
 
      $filter: { 
 
       input: '$roles', 
 
       as: 'role', 
 
       cond: { 
 
        $or: [ 
 
         {$gt: ['$$role.effectiveTo', currentDate]}, 
 
         {$not: {$ifNull: ['$$role.effectiveTo', false]}} 
 
        ] 
 
       } 
 
      } 
 
     }, 
 
     filteredGroups: { 
 
      $filter: { 
 
       input: '$groups', 
 
       as: 'group', 
 
       cond: { 
 
        $or: [ 
 
         {$gt: ['$$group.effectiveTo', currentDate]}, 
 
         {$not: {$ifNull: ['$$group.effectiveTo', false]}} 
 
        ] 
 
       } 
 
      } 
 
     } 
 
    } 
 
}]);

你必須'用戶'屬性與原始文檔和2個附加屬性:filteredGroups和filteredRoles。

+0

它不工作,返回0元素在filteredGroups和filteredRolesobject元素是那裏.. –

+0

@RahulGour請你提供一個文件,應該工作,但它doesn'噸,所以我可以測試。你可以使用http://jsbin.com/ –

+0

太長時間,無法添加評論,你可以告訴我其他方式或如何添加片段 –

相關問題