我正在使用perl MongoDBx :: Class,下面的教程将插入下面的文档。 tags字段是散列数组。尝试使用mongodb的$ pull和$ addToSet函数删除标记并添加标记,但未成功。MongoDB - 在散列数组的字段中添加/删除元素如何
如何向/从标签字段添加/删除元素?如果你不是perl程序员,那么在mongodb shell命令中回答也是可以的。
谢谢。
my $novel = $novels_coll->insert({
_class => 'Novel',
title => 'The Valley of Fear',
year => 1914,
author => {
first_name => 'Arthur',
middle_name => 'Conan',
last_name => 'Doyle',
},
added => DateTime->now(time_zone => 'Asia/Jerusalem'),
tags => [
{ category => 'mystery', subcategory => 'thriller' },
{ category => 'mystery', subcategory => 'detective' },
{ category => 'crime', subcategory => 'fiction' },
],
});
这是插入到文档:
{
"_id": {
"$oid": "4e27eae3008a6ee40f000000"
},
"_class": "Novel",
"added": "2011-07-21T12:01:23+03:00",
"author": {
"middle_name": "Conan",
"last_name": "Doyle",
"first_name": "Arthur"
},
"tags": [
{
"subcategory": "thriller",
"category": "mystery"
},
{
"subcategory": "detective",
"category": "mystery"
},
{
"subcategory": "fiction",
"category": "crime"
}
],
"title": "The Valley of Fear",
"year": 1914
}
编辑:
MongoDBX,overrided官方MongoDB的驱动程序的更新方法,所以$拉的更深层次的探索之后,$ addToSet可能无法正常工作。我会用这个愚蠢的方法:
my $novel = $novel_coll->find_one({ some criteria });
my @tags = $novel->tags;
my @updated_tags = grep(unless($tag{category=>CATEGORY}, @tags); #to pull out unwanted tag. Or use push to add new tag.
$novel->update({tags=>\@updated_tags});
我希望MongoDBx有更新arrayRef字段的方法。
谢谢。如果我使用官方的MongoDB,我在数组中使用了$ pull和$ addToSet,但不知道如何在哈希数组中使用。MongoDBx :: Class有更新方法,可以避免根据官方的MongoDB api设置$。经过一个晚上的探索,我想到了另一个愚蠢的解决方案,作为编辑添加到原始文章。 – Weiyan