删除MongoDB中带有条件的嵌套文档 [英] Remove nested document with condition in MongoDB
问题描述
对于下面的JSON,我如何删除高度最小的狗
For the following JSON how do I remove the dog whose height is the least
{
_id:0
"name":"Andy",
"pets":[
{
"type":"dog","name":"max","height":120
},
{
"type":"dog","name":"rover","height":44
},
{
"type":"dog","name":"katie","height":100
},
{
"type":"cat","name":"minni"
}
]
}
推荐答案
问题是子文档的数组不是集合,不能对其进行排序或做其他事情.但是,如果您可以访问任何语言界面,例如 JavaScript,否则这是可能的.您只需要提取子文档列表,按高度排序,记住第一个,然后根据名称和高度运行命令将其从数组中拉出.例如,可以在 MongoDB shell 中使用此 JavaScript 代码来完成:
The problem is the array of subdocuments is not a collection, you can't sort or do something else on it. But if you have an access to any language interface like JavaScript or else it's possible. You just need to extract list of subdocuments, sort them by height, remember the first one and then run the command to pull it from the array based on its name and height. It can be done for example using this JavaScript code right in the MongoDB shell:
var min = 0; var name = "";
db.animals.find({ query:{"_id" : 0} }).forEach(
function(record){
var sets = record.pets;
min = sets[0].height;
sets.forEach(function(set){
if(set.height <= min)
{min=set.height;
name=set.name;}
});
print(min);
print(name);
query = {"_id": 0}
update = { "$pull" : { "pets" : { "name" : name } } };
db.animals.update(query, update);
})
我怀疑该解决方案不是最优雅的,但无论如何它都有效.
I suspect the solution is not the most elegant but anyway it works.
这篇关于删除MongoDB中带有条件的嵌套文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!