[英]MongoDB update field with another field from another collection
我有两个 collections:书籍和类别。 类别 collections 表示树结构,使它们使用父级和子级嵌套类别。
这本书可以有多个类别并将它们存储在一个数组中。
示例:图书具有类别,我想将其停用并将其设置为父类别。
这就是类别集合的填充方式。
db.categories.insertMany([
{
_id: "Space Opera",
ancestors: ["Science Fiction", "Fiction", "Science Fiction & Fantasy"],
parent: ["Science Fiction"],
},
{
_id: "Dystopian",
ancestors: ["Science Fiction", "Fiction", "Science Fiction & Fantasy"],
parent: ["Science Fiction"],
},
{
_id: "Cyberpunk",
ancestors: ["Science Fiction", "Fiction", "Science Fiction & Fantasy"],
parent: ["Science Fiction"],
},
{
_id: "Science Fiction",
ancestors: ["Fiction", "Science Fiction & Fantasy"],
parent: ["Fiction", "Science Fiction & Fantasy"],
},
{
_id: "Fantasy",
ancestors: ["Science Fiction & Fantasy"],
parent: ["Science Fiction & Fantasy"],
},
{
_id: "Science Fiction & Fantasy",
ancestors: [],
parent: [],
},
{
_id: "Fiction",
ancestors: [],
parent: [],
},
]);
另外,我如何查询这个并只获取值“科幻小说”(注意它存储在一个数组中)?
db.categories.find({_id : "Space Opera"}, {_id : 0, parent : 1})[0].parent // Did not work
db.categories.find({_id : "Space Opera"}, {_id : 0, parent : 1}) // find parent
// result
[
{
"parent": [
"Science Fiction"
]
}
]
db.books.update(
{title : "Book1"},
{$set : {category : [**PARENT CATEGORY**]}}
)
我相信我可以在 books.update() 中使用上面的代码
我可以将它存储在一个单独的变量中,但在 vscode 中它给了我未定义的。 内部查询并没有像前面所说的那样给我正确的值,但我认为你明白了。
db.books.update(
{title : "Book1"},
{$set : {category : [db.categories.find({_id : "Space Opera"}, {_id : 0, parent : 1})]}}
)
您可以使用此聚合管道获得的父级:
db.categories.aggregate([
{ $match: { _id: "Space Opera" } },
{ $project: { _id: 0, parent: { $first: "$parent" } } }
])
甚至
db.categories.aggregate([
{ $match: { _id: "Space Opera" } },
{ $project: { _id: 0, parent: { $first: "$parent" } } }
]).toArray().shift().parent
要加入 collections,您必须使用$lookup运算符。 请记住,NoSQL 数据库(如 MongoDB)未针对连接/查找进行优化。 在现实生活中,您应该寻找更好的设计。
db.books.aggregate([
{ $match: { title: "Book1" } },
{
$lookup:
{
from: "categories",
pipeline: [
{ $match: { _id: "Space Opera" } },
{ $project: { _id: 0, parent: { $first: "$parent" } } }
],
as: "category"
}
},
{ $set: { category: { $first: "$category.parent" } } }
])
如果您想更新现有集合,则必须为其创建一个循环:
db.books.aggregate([...]).forEach(function (doc) {
db.books.updateOne({ _id: doc._id }, { $set: { category: doc.category } });
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.