0

I have this document structure in the collection:

{"_id":"890138075223711744",
"guildID":"854557773990854707",
"name":"test-lab",
"game": {
    "usedWords":["akşam","elma","akım"]
    }
}

What is the most efficient way to get its fields except the array (it can be really large), and at the same time, see if an item exists in the array ?

I tried this:

    let query = {_id: channelID}
    const options = { sort: { name: 1 }, projection: { name: 1, "game.usedWords": { $elemMatch: { word}}}}
    mongoClient.db(db).collection("channels").findOne(query, options);

but I got the error: "$elemMatch can not be used on nested fields"

1 Answer 1

1

If I've understood correctly you can use this query:

Using positional operator $ you can return only the matched word.

db.collection.find({
  "game.usedWords": "akşam"
},
{
  "name": 1,
  "game.usedWords.$": 1
})

Example here

The output is only name and the matched word (also _id which is returned by default)

[
  {
    "_id": "890138075223711744",
    "game": {
      "usedWords": [
        "akşam"
      ]
    },
    "name": "test-lab"
  }
]
Sign up to request clarification or add additional context in comments.

3 Comments

It works ok but if the array does not include the item, the query returns null. I want other fields like "name" to be returned regardless.
Is something like this what are you looking for?
this solves the problem. Credits to Centrax from mongoDB discord server. @J.F.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.