Search code examples
mongodbmongodb-querymongo-shell

Query in MongoDB to return documents matching at least two values in an array


Okay, I've been trying to wrap my head around this for a while and still cannot find the answer. Let's say I have a collection of Mongo documents containing a field with an array of strings called tags.

{
    _id: ObjectId("64fdff612ee6d1467c4501f5"),
    title: "Document1",
    "tags": [
        "tagOne"
    ]
},
{
    _id: ObjectId("64fdff612ee6d1467c4501f6"),
    title: "Document2",
    "tags": [
        "tagOne",
        "tagTwo"
    ]
},
{
    _id: ObjectId("64fdff612ee6d1467c4501f7"),
    title: "Document3",
    "tags": [
        "tagOne",
        "tagTwo",
        "tagThree"
    ]
}

I have no problem returning the documents that contain "tagOne" OR "tagTwo". For example, using

db.getCollection("documents").find({ 'tags': { $in: ['tagOne',tagTwo'] }})

would return all three documents. However, I'm seeking to query for documents that contain at least those two tags. Therefore, a query that would only return the last two documents since they contain at least those two tags (but could contain any other tags as well).


Solution

  • Try with $all which is like an $and: https://www.mongodb.com/docs/manual/reference/operator/query/all/#mongodb-query-op.-all

    db.getCollection("documents").find({ 'tags': { $all: ['tagOne','tagTwo'] }})