处理数据并加入 mongodb
Manipulating data and join mongodb
我对 Mongodb 比较陌生,我需要执行以下操作:
我有 2 tables,“记录”和“文件”。
“记录”中的一行 table 如下所示:
{ "_id" : ObjectId("6012d31aea8fb06d8bf438a0"), "img" : false, "type" : "DRAFT", "submitted" : true }
“文件”中的一行 table 如下所示:
{ "_id" : ObjectId("5fabf23f917863623ec54a86"), "filename" : "6012d31aea8fb06d8bf438a0", "uploadDate" : ISODate("2020-11-11T14:16:31.462Z"), "length" : NumberLong(4119) }
“文件”中的字段“文件名”table对应于“记录”中的_id字段table。
如何在“记录”中找到文件名不是 id 的所有“文件”table?
谢谢!
编辑:* 我正在使用 Mongo 版本 3.6*
- 将
filename
转换为 ObjectId
。
- 使用
filename
和 _id
执行 $lookup
(或加入)操作。
- 保留空
records
(这意味着 records
集合没有该文件的条目)。
试试这个查询:
db.files.aggregate([
{
$lookup: {
from: "records",
let: { file_id: { $toObjectId: "$filename" } },
pipeline: [
{
$match: {
$expr: { $eq: ["$_id", "$$file_id"] }
}
}
],
as: "records"
}
},
{
$match: {
$expr: {
$eq: [{ $size: "$records" }, 0]
}
}
}
])
Mongo 3.6版本:
我创建了一个集合“temp”(稍后我将删除以保存 space):
db.createCollection("temp");
db.records.find().map( function(u) {
db.temp.insert({'strId': u._id.str, 'type': u.type, 'status': u.submitted, 'image': u.img});
});
然后使用与@Dheemanth Bhat 的回答类似的聚合查询它:
db.temp.aggregate([
{
$lookup: {
from: "files",
let: { testId: "$strId" },
pipeline: [
{
$match: {
$expr: { $eq: ["$$testId", "$filename"] }
}
}
],
as: "corresponding_id"
}
},
{
$match: {
$expr: {
$eq: [{ $size: "$corresponding_id" }, 0]
}
}
}
])
我对 Mongodb 比较陌生,我需要执行以下操作:
我有 2 tables,“记录”和“文件”。
“记录”中的一行 table 如下所示:
{ "_id" : ObjectId("6012d31aea8fb06d8bf438a0"), "img" : false, "type" : "DRAFT", "submitted" : true }
“文件”中的一行 table 如下所示:
{ "_id" : ObjectId("5fabf23f917863623ec54a86"), "filename" : "6012d31aea8fb06d8bf438a0", "uploadDate" : ISODate("2020-11-11T14:16:31.462Z"), "length" : NumberLong(4119) }
“文件”中的字段“文件名”table对应于“记录”中的_id字段table。
如何在“记录”中找到文件名不是 id 的所有“文件”table?
谢谢!
编辑:* 我正在使用 Mongo 版本 3.6*
- 将
filename
转换为ObjectId
。 - 使用
filename
和_id
执行$lookup
(或加入)操作。 - 保留空
records
(这意味着records
集合没有该文件的条目)。
试试这个查询:
db.files.aggregate([
{
$lookup: {
from: "records",
let: { file_id: { $toObjectId: "$filename" } },
pipeline: [
{
$match: {
$expr: { $eq: ["$_id", "$$file_id"] }
}
}
],
as: "records"
}
},
{
$match: {
$expr: {
$eq: [{ $size: "$records" }, 0]
}
}
}
])
Mongo 3.6版本:
我创建了一个集合“temp”(稍后我将删除以保存 space):
db.createCollection("temp");
db.records.find().map( function(u) {
db.temp.insert({'strId': u._id.str, 'type': u.type, 'status': u.submitted, 'image': u.img});
});
然后使用与@Dheemanth Bhat 的回答类似的聚合查询它:
db.temp.aggregate([
{
$lookup: {
from: "files",
let: { testId: "$strId" },
pipeline: [
{
$match: {
$expr: { $eq: ["$$testId", "$filename"] }
}
}
],
as: "corresponding_id"
}
},
{
$match: {
$expr: {
$eq: [{ $size: "$corresponding_id" }, 0]
}
}
}
])