Set up four tagged products
Run this once in mongosh on a development server, using an empty practice collection.
const lab = db.getSiblingDB("keplergrid_query_lab")
lab.tagged_products.insertMany([
{ _id: "TAG-101", tags: ["paper", "recycled"] },
{ _id: "TAG-102", tags: ["paper", "archival"] },
{ _id: "TAG-103", tags: ["recycled", "plastic"] },
{ _id: "TAG-104", tags: ["metal"] }
])
In KeplerGrid, connect in Read only mode. Open keplergrid_query_lab.tagged_products in Documents.
Match either tag with $in
Paste this into Filter and click Run. Expect TAG-101, TAG-102, and TAG-103 in the results. Each has at least one requested tag.
{ "tags": { "$in": ["paper", "recycled"] } }
Require both tags with $all
Replace the filter with the version below and run it again. Only TAG-101 has both tags.
{ "tags": { "$all": ["paper", "recycled"] } }
For these string tags, the order in $all does not matter. Products can also have other tags.
Inspect the complete matching array
After either query, choose JSON view in the results toolbar. The matching documents still contain their complete tags arrays. For example, the $in query matches TAG-102 because of paper and still shows archival.
When several conditions must match fields in one embedded object instead of string tags, use $elemMatch. To compare loaded rows with the full match count, count documents that match a filter.
To match how many items an array contains, filter by array length with $size.
Next, Index a MongoDB array field with a multikey index.
Next, Add MongoDB array values without new duplicates with $addToSet.