[英]Fetching data from one table to another in MongoDb
我在 mongo 中有一个名为“sell”的数据库。 现在这个数据库包含两个表“汽车”和“订单”。 在“汽车”表中,我有名为“价格”的属性。 现在当我执行
db.Order.aggregate([
{
$lookup: {
from: "Car",
localField: "carId",
foreignField: "_id",
as: "PRICE",
},
},
{ $unwind: "$PRICE" },]).pretty()
命令在 mongo shell 中,它给出包含“Order”表属性和 PRICE 数组的输出,其中包含“Car”表的所有属性。 现在,我想获取“汽车”表中的“价格”属性。 我当前的输出如下面的链接所示,但我想从“PRICE”中获取“price”。 那么我的命令应该是什么???
我的“汽车”表模型代码是
module.exports = {
tableName: "Car",
schema: true,
attributes: {
carmodel: {
type: "String",
},
stock: {
type: "Number",
},
color: {
model: "Master",
},
code: {
type: "STRING",
unique: true,
},
brakes: {
type: "String",
},
description: {
type: "String",
},
wheels: {
type: "String",
},
carwindow: {
type: "String",
},
carseat: {
model: "Master",
},
engine: {
type: "String",
},
price: {
type: "Number",
},
//self relation
parentId: {
model: "Car",
columnName: "parentId",
},
//OTM
Master: {
collection: "Master",
via: "car",
},
//OTO
order: {
collection: "order",
via: "carId",
},
sellprice: {
collection: "order",
via: "price",
},
},
};
我的“订单”表代码是
const { date } = require("faker");
const Car = require("../models/Car");
module.exports = {
tableName: "Order",
schema: true,
attributes: {
address: { type: "String" },
status: {
model: "Master",
},
orderDate: { type: "string", columnType: "datetime" },
//OTO
carId: {
model: "Car",
unique: true,
},
price: {
model: "Car",
unique: true,
},
//OTM
Master: {
collection: "Master",
via: "order",
},
},
};
我想要的输出是
{"PRICE" : 905000 }
PRICE 是订单中所有汽车价格的总和
db.Order.aggregate([
{
$lookup: {
from: "Car",
let: { carId: "$carId" },
pipeline: [
{ $match: { $expr: { $eq: ["$$carId", "$_id"] } } },
{ $project: { price: 1, _id: 0 } },
],
as: "carInfo",
},
},
{ $unwind: "$carInfo" },
{ $replaceRoot: { newRoot: "$carInfo" } },
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.