我正在尝试使用node.js中的moongose在mongodb中查找子集合,但它会查找所有子记录,我想只查找活动记录。
父集合是用户 子集合 - 包含由用户发布的帖子并具有user_id作为用户集合的引用的帖子。我试过下面的查询,但没有运气
用户收集示例:
{
"_id" : ObjectId("584016e28880811461000007"),
"fname" : "Test",
"lname" : "user",
"email" : "test@user.com",
},
{
"_id" : ,
"fname" : "Test2",
"lname" : "user2",
"email" : "test2@user.com",
}
收集后样本:
{
"_id" : ObjectId("5863aed8cafb42674600000e"),
"user_id" : ObjectId("584016e28880811461000007"),
"title" : "Post 1",
"is_deleted" : false
},
{
"_id" : ,
"user_id" : ObjectId("584016e28880811461000007"),
"title" : "Post 2",
"is_deleted" : true
}
查询我尝试过:
Users.collection.aggregate([
{ $lookup: {from: "Posts", localField: "_id", foreignField: "user_id", as: "Posts"} },
{ $match : { $or : [{"Posts._id" : {$exists : true}, "Posts.is_deleted" : false}] }},
{$project: {fname: "$fname", lname : "$lname", email : "$email", "publishedPosts" : {$size : "$Posts"}}}
])
我从上面的代码得到的结果:
[
{"fname" : "Test", "lname" : "user", "email" : "test@user.com", "publishedPosts" : 2},
{"fname" : "Test2", "lname" : "user2", "email" : "test2@user.com", "publishedPosts" : 0}
]
结果预期:
[
{"fname" : "Test", "lname" : "user", "email" : "test@user.com", "publishedPosts" : 1},
{"fname" : "Test2", "lname" : "user2", "email" : "test2@user.com", "publishedPosts" : 0}
]
查找所有帖子,其中is_deleted为false或true
请帮我查一些对我有用的类似查询
答案 0 :(得分:1)
你正在使用的$ match阶段是错误的。第一个条件({"Posts._id" : {$exists : true}
)是无用的,因为每个文档都必须有一个_id字段(有关详细信息,请参阅mongodb _id field)。
更新:在$ lookup之前进行$ match阶段以获得更好的表现。从帖子到用户查找,然后展开用户和组文档以获得总和
此查询返回您期望的结果:
db.Posts.aggregate([
{
$match:{
is_deleted:false
}
},
{
$lookup:{
from:"Users",
localField:"user_id",
foreignField:"_id",
as:"Users"
}
},
{
$unwind:"$Users"
},
{
$group:{
_id:"$user_id",
lname:{
$first:"$Users.lname"
},
fname:{
$first:"$Users.fname"
},
email:{
$first:"$Users.email"
},
publishedPosts:{
$sum:1
}
}
}
])
输出:
{ "_id" : ObjectId("584016e28880811461000007"), "lname" : "user", "fname" : "Test", "email" : "test@user.com", "publishedPosts" : 1 }
答案 1 :(得分:0)
你可以尝试这个,它正常工作
商店收藏
{
name:"shop1",
status:true,
_id : ObjectId("583d0c1f2bd2cbdb117053c5")
}
{
name:"shop2",
status:false,
_id : ObjectId("583d0c1f2bd2cbdb117053c6")
}
订单收集
{
orderNo:1,
price:100,
product:"product1",
shop:ObjectId("583d0c1f2bd2cbdb117053c5")
}
试试这个
db.getCollection('orders').aggregate([
{
$lookup:
{
from: "shop",
localField: "shop",
foreignField: "_id",
as: "shopData"
}
},
{ $match : { $or: [ { "shopData.status": true}] } }
])
结果:
[{
orderNo:1,
price:100,
product:"product1",
shop:[{
name:"shop1",
status:true,
_id : ObjectId("583d0c1f2bd2cbdb117053c5")
}]
}]