1

任何人都可以帮助我创建 mongo 查询以删除 "name" : "gdfgdfgdfg" 嵌入文档

如下存储在 Mongo db 中的对象。

{
    "_id": ObjectId("50656f33a4e82d3f98291eff"),
    "description": "gdfgdfgdfg",
    "menus": [
    {
        "name": "gdfgdfgdfg"**,
        "description": "dfgdgd",
        "text": "dfgdfg",
        "key": "2",
        "onSelect": "yyy",
        "_id": ObjectId("50656f3ca4e82d3f98291f00")
    },
    {
        "name": "dfg",
        "description": "dfgdfgdfgdf",
        "text": "dfgdgf",
        "key": "1",
        "onSelect": "uuuu",
        "_id": ObjectId("50656f44a4e82d3f98291f01")
    }
    ]
}

任何人都可以帮助我,我是Mongo的新手

4

3 回答 3

1

在 JavaScript shell 中,您可以这样做:

var query = {"_id": ObjectId("50656f33a4e82d3f98291eff")};
db.collection.update(query, {'$pull':{ menus: {name : 'gdfgdfgdfg'} } });

或使用 ID。

db.collection.update(query, {'$pull': { menus: {"_id": ObjectId("50656f3ca4e82d3f98291f00")} } });

使用 Java 驱动程序应该是这样的:

BasicDBObject query = new BasicDBObject("_id", new ObjectId("50656f33a4e82d3f98291eff"));

BasicDBObject docToRemove = new BasicDBObject("name", "gdfgdfgdfg");

BasicDBObject updateCommand = new BasicDBObject("$pull", new BasicDBObject("menus", docToRemove));

collection.update(query, updateCommand);
于 2012-09-28T11:19:18.920 回答
0

Mongo 不会让您删除嵌入的文档。您需要做的是从集合中取出对象,删除列表中的一个对象,然后将其保存回数据库。

obj = db.collection.findOne({"_id": ObjectId("50656f33a4e82d3f98291eff")});
menus = obj.menus.splice(0,1); // Or some other way to manually delete
                               // the one item in the list
db.collection.update({"_id": ObjectId("50656f33a4e82d3f98291eff")},
                     {$set: {menus: menus}});

很复杂,看这里

编辑:如果你不知道索引,你可以试试这个:

obj = db.collection.findOne({"_id": ObjectId("50656f33a4e82d3f98291eff")});
var i = 0;
for(i=0;i<obj.menus.length;i++) {
    if(obj.menus[i].name === "gdfgdfgdfg")
        break;
}
menus = obj.menus.splice(i,1);
db.collection.update({"_id": ObjectId("50656f33a4e82d3f98291eff")},
                     {$set: {menus: menus}});
于 2012-09-28T10:41:05.687 回答
-1
$conditionArray=array("_id"=>ObjectId("50656f33a4e82d3f98291eff"));
$dataArray=array("description"=>"");
$db->$collectionName->update($conditionArray,array('$unset' =>$dataArray))->limit(1);
于 2012-09-28T10:36:51.630 回答