我有三个猫鼬模特
当用户喜欢某些内容时,它会保存在Liked集合中。但我想做的是。进行查询,提供用户之前不喜欢的10种可用产品,而不是他自己的产品。我无法弄清楚如何在一个查询中实现这一点。会不可能?
用户:
<div id="banner"></div>
<style>
#banner {
background:url('.png');
width:100%;
height:192px;
background-size:100%;
background-repeat: no-repeat;
margin-left: auto;
margin-right: auto;
}
</style>
产品:
{
password: String,
type: {
type: String,
enum: ['user', 'admin'],
required: true,
default: "user"
},
firstName: {type: String},
middleName: {type: String},
lastName: {type: String},
gender: {type: String},
profilePicture: {type: Object},
setOwnProfilePicture: {type: Boolean, default: false},
facebook:{
id: {type: String},
token: {type: String}
}
}
喜欢:
{
condition: {
type: String,
enum: ['Als nieuw', 'Goed', 'Redelijk', 'Matig'],
required: true,
default: "Goed"
},
type: {
type: String,
enum: ['Ruilen', 'Doneren'],
required: true,
default: "Ruilen"
},
zipCode: {type: String},
houseNumber: {type: String},
distance: {type: Number},
likes: {type: Number, default: 0},
dislikes: {type: Number, default: 0},
title: {type: String},
description: {type: String},
owner: {type: Schema.ObjectId},
images: { type : Array , "default" : [] }
}
更新:
我找出了要使用的查询,但在结果中我有一个名为{
ownerProductID: {type: Schema.ObjectId},
productID: {type: Schema.ObjectId},
liked: Boolean
}
的字段,但我想过滤掉它,所以我不会在结果中获得任何额外的值。
我现在使用的查询:
liked
答案 0 :(得分:1)
使用聚合在多个级别上进行过滤。
假设您拥有USER_OBJECTID
,首先过滤所有者的产品,然后将该集合加入Liked
并再次使用用户ID过滤。
db.Product.aggregate([
{$match: {'owner': {$ne: '<USER_OBJECTID>'}}},
{$lookup: {
from: 'liked',
localField: '_id',
foreignField: 'productID',
as: 'likes'
}
},
{$match: {'likes.userID': {$nin: [<USER_OBJECTID>]}}},
{$limit: 10}
])
答案 1 :(得分:1)
我设法得到了我想要的结果。使用此查询:
db.products.aggregate(
[
{
$match: {'owner': {$ne: ObjectId("583f2f33ee975f4e8560b9fe")}}
},
{
$lookup: {
"from" : "likes",
"localField" : "_id",
"foreignField" : "productID",
"as" : "liked"
}
},
{
$match: {'liked.ownerProduct': {$nin: [ObjectId("585834609bb1aa1cbe98257b")]}}
},
{
$limit: 10
},
{
$project: {
_id: 1,
owner: 1,
zipCode: 1,
title: 1,
description: 1,
houseNumber: 1,
images: 1,
dislikes: 1,
likes: 1,
type: 1,
condition: 1
}
},
]
);