一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

MongoDB更新多级文档的数据代码示例

时间:2021-06-22 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下MongoDB更新多级文档的数据代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

嵌套数组更新

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

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

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

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

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

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

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

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

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

更新下级文档的属性

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

{
  name: '岛上码农', 
  scores: {
    view:  18800, 
    praise: 290, 
    followers: 105
	}
}
db.author.update(
  {name: '岛上码农'}, 
  {'$set': {'scores.praise': 291}}
);

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

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

属性增加和移除

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

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

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

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

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

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

热门栏目