2016-10-27 109 views
0

我有一个Mongo集合,它由一个文档和一个嵌套对象组成,它描述了文档在什么集合以及何时添加。我想根据条件从嵌套对象中删除键值对,例如是1-1-2016之前的值(日期)。Mongo从嵌套对象中删除值

实施例:

{ 
    "_id" : ObjectId("581214940911ad3de98002db"), 
    "collections" : { 
     "c01" : ISODate("2016-10-27T15:52:04.512Z"), 
     "c02" : ISODate("2015-11-21T16:06:06.546Z") 
    } 
} 

需要成为

{ 
    "_id" : ObjectId("581214940911ad3de98002db"), 
    "collections" : { 
     "c01" : ISODate("2016-10-27T15:52:04.512Z"), 
    } 
} 

一个替代方案将是到模式改变到这样的事情:

{ 
    "_id" : ObjectId("581214940911ad3de98002db"), 
    "collections" : [ 
     { 
      "id": "c01", 
      "date": ISODate("2016-10-27T15:52:04.512Z") 
     }, 
     { 
      "id": "c02", 
      "date" : ISODate("2015-11-21T16:06:06.546Z") 
     } 
    ] 
} 

在这种情况下,除去从原稿一个会很容易。我有点不愿意这样做,因为这会使我想支持的其他一些查询复杂化。谢谢!

+0

如果更改架构你会做你自己一个大忙第二结构。 – styvane

回答

0

我希望为自己的模式

{ 
    "_id" : ObjectId("581214940911ad3de98002db"), 
    "collections" : [ 
     { 
      "id": "c01", 
      "date": ISODate("2016-10-27T15:52:04.512Z") 
     }, 
     { 
      "id": "c02", 
      "date" : ISODate("2015-11-21T16:06:06.546Z") 
     } 
    ] 
} 

然后能够从collections删除这样

db.collectionName.update(
    { },// if you want can add query for specific Id {"_id" : requestId}, 
    { $pull: { collections: { date: {$lt: yourDate} } } }, // if need can convert iso date string like: new Date(yourDate).toISOString() 
    { multi: true } 
)