英文:
MongoDB - embedding, inserting one collection into another
问题
如果我有一个集合(例如名为people)看起来像这样:
{
_id: ObjectID("5e12f6260c190f8ee91b162d"),
name: "Joe Bookreader",
address: "Highway To Hell 21"
}
并且我想要删除address的值,并将集合(addresses)嵌入其中:
{
_id: ObjectID("5e25fg3gjh48ee91b2653"),
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
}
使其看起来像这样:
{
_id: ObjectID("5e12f6260c190f8ee91b162d"),
name: "Joe Bookreader",
address: [
{
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
}
]
}
我该如何做?
是否类似于插入新列,就像下面的代码一样(或者完全不同)?
var bulkInsert = db.people.initializeUnorderedBulkOp()
db.addresses.find().forEach(
function(doc){
bulkInsert.insert(doc);
}
)
任何帮助都将不胜感激,谢谢!
英文:
If I have a collection (named e.g. people) that looks like
{
_id: ObjectID("5e12f6260c190f8ee91b162d"),
name: "Joe Bookreader",
address: "Highway To Hell 21"
}
and I want to remove this value for address, and embed the collection (addresses) into it:
{
_id: ObjectID("5e25fg3gjh48ee91b2653"),
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
}
to look like:
{
_id: ObjectID("5e12f6260c190f8ee91b162d"),
name: "Joe Bookreader",
address: [
{
street: "123 Fake Street",
city: "Faketon",
state: "MA",
zip: "12345"
}
]
}
How would I do this?
Would it be something similar to inserting the new column, like in the code below (or something completely different)?
var bulkInsert = db.people.initializeUnorderedBulkOp()
db.addresses.find().forEach(
function(doc){
bulkInsert.insert(doc);
}
)
Any help would be appreciated, thanks!
答案1
得分: 2
你可以运行$lookup with empty pipeline
,将一个集合嵌入到另一个集合中。
db.people.aggregate([
{
$lookup: {
from: "addresses",
pipeline: [ ],
as: "addresses"
}
}
])
然后,你可以使用$out(完全替换输出集合为聚合结果)或$merge(将聚合结果合并到现有集合中)。
编辑:
你可以添加$match
以定位单个文档,而不是整个集合:
db.people.aggregate([
{
$lookup: {
from: "addresses",
pipeline: [ { $match: { street: "123 Fake Street" } } ],
as: "addresses"
}
}
])
英文:
You can run $lookup with empty pipeline
to embed one (entire collection) into another.
db.people.aggregate([
{
$lookup: {
from: "addresses",
pipeline: [ ],
as: "addresses"
}
}
])
Then you can either use $out (replace the output collection entirely with aggregation result) or $merge (incorporates aggregation results into existing collection):
EDIT:
You can add $match
to target single document instead of entire collection:
db.people.aggregate([
{
$lookup: {
from: "addresses",
pipeline: [ { $match: { street: "123 Fake Street" } } ],
as: "addresses"
}
}
])
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论