查询mongodb以获取条件 [英] Query mongodb for conditional conditions
问题描述
如何查询mongo以获得所有非私有博客以及当前登录用户的私有博客的列表.
How do i query mongo for the list of all non-private blogs along with the private blogs of currently logged-in user.
博客(收藏):
_user_id: ref(User),
title: String,
body: String,
private: Boolean, default:false
Blog(collection):
_user_id: ref(User),
title: String,
body: String,
private: Boolean, default:false
我可以使用以下查询获取所有非私有博客:
I can get all the non-private blogs with this query:
Blog.find({_user_id: req.user}).where('private', false).exec();
但是我也想获取所有仅由当前登录用户标记为私有的博客.
But I also want to get all the blogs which are marked private only by this current logged-in user.
使用单个查询甚至可以做到这一点.我是否必须依赖诸如map-reduce/gregation之类的高级mongodb功能.
Is this thing even possible using single query. Do I have to rely on advance mongodb features like map-reduce / aggregate .
推荐答案
您可以使用 $or
可以在单个查询中包括这两种情况:
You can use $or
to include both cases in a single query:
Blog.find({$or: [
// Non-private blogs
{private: false},
// Blogs of the current user
{_user_id: req.user}
]}).exec(function(err, docs) { ... });
这将提供两个$or
子句的结果的并集.
This will provide a union of the results of the two $or
clauses.
这篇关于查询mongodb以获取条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!