gpt4 book ai didi

java - 如何在 Mongo 中创建嵌入对象的查询?

转载 作者:行者123 更新时间:2023-12-01 05:06:07 28 4
gpt4 key购买 nike

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

Mongo 数据库中存储的对象如下。

{
"_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 新手

最佳答案

在 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);

关于java - 如何在 Mongo 中创建嵌入对象的查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12638291/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com