如何在Cloudant/CouchDB中实现类似SQL多IN条件的文档查询?
Absolutely, you can pull off this multi-IN condition query in Cloudant/CouchDB—no problem at all! Let me walk you through exactly how to do it, since it’s straightforward once you know the right tools.
IN) in Cloudant/CouchDB Your exact requirement (countryCode IN ["US","AR", "UK"] AND status IN ["Pending", "Error", "Loading"]) is fully achievable, and the cleanest way to do it is using Mango queries—the modern, ad-hoc query language for Cloudant/CouchDB.
Using Mango Query (Recommended)
Mango natively supports the $in operator, which works exactly like SQL's IN clause. Here's the direct translation of your SQL filter into a Mango selector:
{ "selector": { "countryCode": { "$in": ["US", "AR", "UK"] }, "status": { "$in": ["Pending", "Error", "Loading"] } }, "fields": ["_id", "_rev", "countryCode", "status"] // Add any other fields you want returned }
Quick Tips for Mango:
- By default, all conditions in the selector are combined with
AND—perfect for your use case. If you ever needORlogic, wrap conditions in a$orblock. - To make this query fast, create a composite index for the fields you're filtering on. Here's how to create that index via Mango:
{ "index": { "fields": ["countryCode", "status"] }, "name": "country-status-index", "type": "json" } - You can extend this pattern to as many
$inconditions as needed. For example, adding a version filter likeversion IN ["V1", "V3", "V5"]is just adding another line to the selector:"version": { "$in": ["V1", "V3", "V5"] }
Alternative: MapReduce Views (Legacy Approach)
If you're working with an older CouchDB setup or prefer MapReduce, you can also achieve this—though it's less clean for multi-IN scenarios.
Map Function
First, create a view that emits the combination of your filter fields:
function(doc) { // Only emit docs that have both fields we care about if (doc.countryCode && doc.status) { emit([doc.countryCode, doc.status], doc); } }
Query the View
To filter for your specific values, you'd pass a list of all valid [countryCode, status] pairs as keys:
?keys=[["US","Pending"],["US","Error"],["US","Loading"],["AR","Pending"],["AR","Error"],["AR","Loading"],["UK","Pending"],["UK","Error"],["UK","Loading"]]
This works, but it gets messy quickly as your IN lists grow—stick with Mango unless you have a specific reason to use views here.
Final Confirmation
Yes, your exact requirement is 100% implementable in Cloudant/CouchDB. The $in operator in Mango makes multi-field IN conditions just as easy as they are in SQL.
内容的提问来源于stack exchange,提问作者Boris Daich

