简体   繁体   English

如何在猫鼬中添加条件?

[英]How to add condition in mongoose?

I need a mongoose query, to select only one record in or condition.我需要一个猫鼬查询,在或条件中只选择一个记录。 There is a collection of blogs.有一个博客集合。 Some of them are in English or in French.其中一些是英文或法文。 Certain blogs are a duplicate like they have the same content but in a different language.But they have same 'group_id'.某些博客是重复的,因为它们具有相同的内容但使用不同的语言。但它们具有相同的“group_id”。

If I filter blogs based on some criteria, like 'category' only blogs with the 'userLanguage' should show.如果我根据某些条件过滤博客,例如“类别”,则只应显示带有“userLanguage”的博客。 But if there is no, show the other language.但如果没有,请显示其他语言。 How do I generate a mongoose query for this?如何为此生成猫鼬查询?

db.find($and:[{category:'Health'},{$or: [{language: 'en'},{language:'fr'}]}])

But it gives 2 records if both 'en' and 'fr' is present, I need only either 'en' or 'fr'.但是如果'en'和'fr'都存在,它会给出2条记录,我只需要'en'或'fr'。 How can I implement this in one query ?如何在一个查询中实现这一点?

These are some sample documents,这些是一些示例文件,

"{_id: '1', category_id: 'xyz', language:'en', group_id: 'aaa'} ", 
"{_id: '2', category_id: 'xyz', language:'fr', group_id: 'aaa'}",
"{_id: '3', category_id: 'xyz' language: 'en', group_id: 'bbb'}",
"{_id: '4', category_id: 'xyz', language: 'fr', group_id: 'ccc'}"

I request for category_id : 'xyz' and language: 'en'.我请求 category_id :'xyz' 和语言:'en'。 So the result should be,所以结果应该是

"{_id: '1', category_id: 'xyz', language:'en', group_id: 'aaa'} ", 
"{_id: '3', category_id: 'xyz' language: 'en', group_id: 'bbb'}",
"{_id: '4', category_id: 'xyz', language: 'fr', group_id: 'ccc'}"

I have an array of distinct group_id = ['aaa','bbb','ccc'].我有一组不同的 group_id = ['aaa','bbb','ccc']。 So the condition is like,所以条件就像,

group_id: $in:group_id $$ language  should be 'en' if not 'fr'

使用 findOne 查询,它只给你一个结果,像这样

db.findOne($and:[{category:'Health'},{$or: [{language: 'en'},{language:'fr'}]}]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM