如何在猫鼬中将AND与OR结合? [英] How to combine AND with OR in mongoose?

查看:97
本文介绍了如何在猫鼬中将AND与OR结合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我意识到,在node.js中,我会建立一个查询,例如:

I realized that when in node.js I build a query such as:

if (hashtagsInput != undefined) {
    var hashtags = hashtagsInput.split(",");
    for(var i=0; i<hashtags.length; i++) {
        query = query.or([{ 'hashtags': hashtags[i] }]);
    }
}

if (friends != undefined) {
    var friendsSplitted = friends.split(",");
    for(var i=0; i<friendsSplitted.length; i++) {
        query = query.or([{ 'facebook_username': friendsSplitted[i] }]);
    }
}

然后查询为:

..., '$or': [ { hashtags: 'test1' }, { hashtags: 'test2' }, {
     facebook_username: 'XXXXXXXXXXXX' }, { facebook_username: 'YYYYYYYYYYYYYYY' },
     { facebook_username: 'ZZZZZZZZZZZZ' }],...

,它将查找所有具有#h0标签或test2标签或具有fb_username XXXXXXYYYYYYYZZZZZZZ的记录.

and that will find all records that either have hashtags test1 or test2 OR have fb_username XXXXXX or YYYYYYY or ZZZZZZZ.

但是我如何在node.js代码中编写查询,以便当用户放置标签时,查询将提取具有test1test2并且fb_username XXXXXXYYYYYYYZZZZZZZ的条目?

But how can I write in the node.js code the query so that when user puts hashtags then the query fetches entries that have test1 or test2 AND fb_username XXXXXX or YYYYYYY or ZZZZZZZ?

如果用户不提供任何标签,则只能获取fb_accounts,反之亦然-如果用户不提供标签,则仅关注标签.

If user does not provide any hashtags then it could fetch only fb_accounts and the other way around - if user does not provide fb, then it pays attention only to hashtags.

推荐答案

我假设您希望在同时提供哈希和用户名时将AND运算符放在哈希和用户名之间,而当同时提供其中一个时,您只希望使用它们进行搜索. /p>

I suppose you want to put AND operator between hashes and username when both are provided, and when one of them is provided you want to search with them only.

var query = {};
query.$and = [];

if (hashtagsInput != undefined) {
    var hashtags = hashtagsInput.split(",");
    query.$and.push({"hashtags":{$in: hashtags}});
}

if (friends != undefined) {
    var friendsSplitted = friends.split(",");
    query.$and.push({"facebook_username":{$in: friendsSplitted}});
}

您可以使用$ in运算符来应用Or条件,因为您可以直接传递数组,而无需申请循环.

You can use $in operator to apply Or condition as you can pass directly array, you don't need to apply for loop.

当用户同时输入主题标签和用户名时,查询将提取具有(test1或test2)AND(fb_username XXXXXX或YYYYYYY或ZZZZZZZ)的条目

When user puts hashtags and username both then the query fetches entries that have (test1 or test2) AND (fb_username XXXXXX or YYYYYYY or ZZZZZZZ)

这篇关于如何在猫鼬中将AND与OR结合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆