0

This seems as though it should be simple but I have been struggling with this for a while with no luck.

Let's assume I have a simple document that looks like the following:

{
  data: [
    {
      name: "Minnesota",
    },
    {
      name: "Mississippi",
    },
    ...
  ]
}

If I run the following query in my Mongo Shell, everything works as I would expect:

db.collection.find({}, {data: {$elemMatch: {name: "Michigan"}}})

Returns:

{ "_id" : ObjectId("5e9ba60998d1ff88be83fffe"), "data" : [ { "name" : "Michigan" } ] }

However, using mongoid, attempting to run a similar query returns every object inside of the data array. Here is one of the may queries I've tried:

Model.where({data: {"$elemMatch": {name: "Michigan"}}}).first

As I mentioned above, that little query returns everything inside the data array, not the specific object I'm trying to pull out of the document.

Any help would be appreciated. I'm trying to avoid returning the results and post-processing them with Ruby. I'd love to handle this at the DB level.

Thank you.

2
  • Your first example does the $elemMatch in the projection, while your second example does it as part of the filter. Does your Model.where() have to ability to control projection? Commented Apr 19, 2020 at 4:10
  • I didn't want to be too wordy in my question, but ya, I've even tried the following: db = Mongoid.default_client.database collection = db[:collection] and collection.find({}, {data: {"$elemMatch": {name: "Michigan"}}}) - no luck. Thank you for the reply. Commented Apr 19, 2020 at 16:54

2 Answers 2

1

There was a very similar question earlier for a different driver. Apparently the ruby driver behaves differently than the shell.

Try running your find as the equivalent database command:

session.command({'find' => 'my_collection', 'filter' => {}, projection => {data: {$elemMatch: {name: "Michigan"}}}})
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. Works like a charm! Thank you!
0

Mongoid syntax for projections is only.

Comments

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.