简体   繁体   中英

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'.

If I filter blogs based on some criteria, like 'category' only blogs with the 'userLanguage' should show. 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'. 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'. 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']. 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'}]}]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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