【发布时间】:2018-08-12 14:39:06
【问题描述】:
我正在尝试以下方法
从日志中找到用户输入的所有奖品 返回订单号和标题
我正在使用 mongo 聚合框架。
- 我通过 userId 匹配
- 我将奖品按同一产品分组,然后推送订单号
- 我想查看奖品收藏以找到奖品的名称。
查找没有返回任何元素
这里是聚合代码
db.pointslogs.aggregate(
// Pipeline
[
// Stage 1
{
$match: {
"user": ObjectId("5aacff47c67f99103bcbf693")
}
},
// Stage 2
{
$group: {
_id: "$productPurchased",
orderNumber: { $push: "$orderNumber" }
}
},
// Stage 3
{
$unwind: {
path : "$orderNumber",
}
},
// Stage 4
{
$lookup: {
"from" : "prizes",
"localField" : "_id",
"foreignField" : "_id",
"as" : "title"
}
},
]
// Created with Studio 3T, the IDE for MongoDB - https://studio3t.com/
);
这里是模型(下面的点日志)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
orderNumber: {type: String, required: true},
productPurchased: {type: String, require: true},
answer: {type: String},
user: [{type: Schema.Types.ObjectId, ref: 'User'}]
});
module.exports = mongoose.model('PointsLog', schema);
奖品如下
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var schema = new Schema({
title: {type: String, required: true},
content: {type: String, required: true},
orderNumber: {type: String, required: true},
imageUrl: {type: String, required: true},
stockQty: {type: Number, required: true},
question: {type: String, required: true},
answers: [{type: String, required: true}],
image: {type: String, required: true},
cost: {type: Number, required: true },
//entries: {type: Int},
//user: {type: Schema.Types.ObjectId, ref: 'User'}
user: [{type: Schema.Types.ObjectId, ref: 'User'}]
});
module.exports = mongoose.model('Prize', schema);
不知道为什么查找没有返回任何内容
【问题讨论】:
-
productPurchased是您的架构中定义的“字符串”。您希望与"prizes"集合匹配的内容是什么?如果您认为它“看起来像”目标集合具有的ObjectId,就像它的_id字段一样,请再看一遍。字符串和Objectid值是不同的,无论您如何“漂亮地打印”它们。出示两份文件,如果您仍然不明白,请指出您希望匹配的内容。 -
productPurchased 是奖品的 _id 但它存储为 string ,所以我认为您所说的是在聚合框架中您无法将字符串与 objectId 匹配,因此最好在编写时要存储为 objectId ant 的日志不是字符串?
-
见Update MongoDB field using value of another field。如果不循环集合中的所有文档、通过函数转换为
ObjectId并将数据写回,则没有其他方法可以“更新”集合中的字段。