Mongodb 在嵌套数组内、集合内按_id删除
这是我的mongoDb足球运动员系列:Mongodb 在嵌套数组内、集合内按_id删除,mongodb,express,Mongodb,Express,这是我的mongoDb足球运动员系列: [ { "_id" : ObjectId("5d83b4a7e5511f28847f1884"), "prenom" : "djalil", "pseudo" : "dja1000", "email" : "djalil@gmail.com", "selectionned" : [ { "_id" : "5d83
[
{
"_id" : ObjectId("5d83b4a7e5511f28847f1884"),
"prenom" : "djalil",
"pseudo" : "dja1000",
"email" : "djalil@gmail.com",
"selectionned" : [
{
"_id" : "5d83af3be5511f28847f187f",
"role" : "footballeur",
"prenom" : "Gilbert",
"pseudo" : "Gilbert",
},
{
"_id" : "5d83b3d5e5511f28847f1883",
"role" : "footballeur",
"prenom" : "Xavier",
"pseudo" : "xav4544",
}
]
},
{
"_id" : ObjectId("5d83afa8e5511f28847f1880"),
"prenom" : "Rolande",
"pseudo" : "Rolande4000",
"email" : "rolande@gmail.com",
"selectionned" : [
{
"_id" : "5d83b3d5e5511f28847f1883",
"role" : "footballeur",
"prenom" : "Xavier",
"pseudo" : "xav4544",
}
]
}
}
我如何删除所有收藏中具有5D83B3D5E551F28847F1883 _id的选定人员
我确实需要xavier从任何“selectionned”数组中删除eapper,就像在SQL语言中执行“delete cascade”一样
这是我尝试过的,但运气不佳:
function delete_fb_from_all(fb){
var ObjectId = require('mongodb').ObjectID; //working
var idObj = ObjectId(fb._id); //working
try {
db.collection('footballers').remove( { "selectionned._id" : idObj } );
console.log('All have been erased');
} catch (e) {
console.log(e);
}
}
这也是行不通的:
db.collection('footballers.selectionned').remove( { "_id" : idObj } );
我真的不知道怎么做
我现在正在尝试:
db.collection.update({'footballers.selectionned': idObj }, {$pull: {footballers:{ selectionned: idObj}}})
这就是错误:
TypeError: db.collection.update is not a function
我认为解决办法可能就在那里:
编辑1
我目前正在尝试:
var ObjectId = require('mongodb').ObjectID; //working
var idObj = ObjectId(fb._id); //working
try {
db.collection('footballers').update(
{ },
{ $pull: { selectionned: { _id: idObj } } },
{ multi: true }
)
} catch (e) {
console.log(e);
}
已解决:
指定电子邮件,它现在正在工作,我猜问题来自_id字段:
try {
db.collection('footballers').update(
{ },
{ $pull: { selectionned: { email: fb.email } } },
{ multi: true }
)
} catch (e) {
console.log(e);
}
对象ID:
问题可能在于对象id的创建。无需使用mongoDB对象id创建字符串id
//不需要
var ObjectId=require('mongodb')。ObjectId;
var idObj=ObjectId(fb.\u id);
//像普通字符串一样执行
db.collection('footballers')。移除({“selectionned.\u id”:fb.\u id});