MongoDB更新修改内嵌文档操作

嵌套数组更新

插入内嵌数组

db.storage.insertMany( [
   { name: "Storage Alpha", items: [ { category: "food",name:"apple" }, {category:"food",name:"banana"},{category:"tool",name:"hammer"},{category:"furniture",name:"couch"}]},
]);

 

以下面的数据(数据集名称为author)为例:

1
{name: '岛上码农', documents: ['Flutter入门与实战', '高性能MySQL', 'MongoDB专业指北']}

我们需要将 MongoDB专业指北改成MongoDB不专业指北,就属于修改嵌套的文档数据了。这个时候需要使用到 MongoDB 提供的定位操作符$。定位操作符即表示将对应条件匹配到的数据,如:

1
2
3
4
db.author.update(
  {name: '岛上码农', documents: 'MongoDB专业指北'},
  {'$set': {'documents.$': 'MongoDB不专业指北'}}
);

对于下级节点为数组的也是一样。

1
2
3
4
5
6
7
8
{
  name: '岛上码农',
  documents: [
    {name: 'Flutter入门与实战', score: 80},
    {name: '高性能MySQL', score: 90},
    {name: 'MongoDB专业指北', score: 85}
  ]
}

需要将 documengs 节点的 name 和 score 进行修改。

1
2
3
4
5
6
7
db.author.update(
  {name: '岛上码农', 'documents.name': 'MongoDB专业指北'},
  {'$set': {
        'documents.$.name': 'MongoDB不专业指北',
        'documents.$.score':88}
  }
);

$定位操作符即在查询条件中找到的数组中的数据元素位置,即表示操作的是该位置的数据。

更新下级文档的属性

更新下级文档属性时可以直接使用属性访问符“.”,例如下面需要更新 praise 增加到291。

1
2
3
4
5
6
7
8
{
  name: '岛上码农',
  scores: {
    view:  18800,
    praise: 290,
    followers: 105
    }
}
1
2
3
4
db.author.update(
  {name: '岛上码农'},
  {'$set': {'scores.praise': 291}}
);

下级文档若还存在嵌套数组也是类似的操作,如下面的数据,需要将“公众号”换成“微信公众号”:

1
2
3
4
5
6
7
8
9
{
  name: '岛上码农',
  scores: {
    view:  18800,
    praise: 290,
    followers: 105,
    platform: ['掘金', '公众号']
    }
}
1
2
3
4
db.author.update(
  {'name': '岛上码农', 'scores.platform': '公众号'},
  {'$set': {'scores.platform.$':'微信公众号'}}
);

属性增加和移除

MongoDB提供了 $push 和 $pull操作指令来增加或移除属性,同时还提供了 $pop 来移除数组的第一个或最后一个值。我们给前一个文档增加一个 homepage 属性。

1
2
3
4
db.author.update(
  {name: '岛上码农'},
  {$push: {homepage: 'https://juejin.cn/user/70787819648695'}}
);

还可以使用$addToSet对内嵌的对象数组进行处理

  

> db.author.updateOne(

  {"chapter":"test"},

  {"$addToSet":{"finalWords":{"word":"abcde","desc":"abcde"}}}

)

 

注意的是,此时插入的是一个名为 homepage 的数组,其中的一个元素是:juejin.cn/user/707878…。如果是增加不是数组的属性,使用$set 指令即可。 可以使用 pull 移除掉匹配的一个属性。

1
2
3
4
db.author.update(
  {name: '岛上码农'},
  {$pull: {homepage: 'https://juejin.cn/user/70787819648695'}}
);
 db.guest.updateOne(
  {"chapter":"test"},
  {"$pull":{"emails":{"word":"abcde"}}}
)

$pop 操作时使用数字-1和1表示移除首尾的元素,对于下面的数据,移除数组platform里的数据。

1
2
3
4
5
6
7
8
9
{
  name: '岛上码农',
    scores : {
        view: 18800,
        praise: 290,
        followers: 105,
        platform: ['掘金', '公众号', '其他1', '其他2']
    }
}
 
1
2
3
4
// 移除第一个元素
db.author.update({name: '岛上码农'}, {$pop: {'scores.platform': -1}});
// 移除最后一个元素
db.author.update({name: '岛上码农'}, {$pop: {'scores.platform': 1}});

 

posted @ 2022-02-11 08:19  晨曦与晚霞之间  阅读(963)  评论(0编辑  收藏  举报