0

I'm a little bit stuck with a query in mongodb and I think I am just looking for it wrong. What I am trying to do is run a query which returns all documents where a value for a specific field is somewhere in an Array.

It's not $in, because this checks an Array field for a specific value. I am trying to do the opposite. I want to do the operation on a String field and look inside an Array. I hope you understand what I mean, but I think it will become clear with an example.

Example:

{
  hero: "The Flash",
  name: "Barry Allen",
  city: "Central City"
},
{
  hero: "Green Arrow",
  name: "Oliver Queen",
  city: "Star City"
},
{
  hero: "Batman",
  name: "Bruce Wayne",
  city: "Gotham City"
}

So assume I want all the heroes active in both Gotham City and Central City. I want do a query where city is in ["Gotham City", "Central City"].

1
  • You requested an 'AND' condition, but I think you want an 'OR' condition. Looking at your example there are no heros in Gotham City AND Central City, but there are two heros in Gotham City OR Central City. Please confirm. Commented Jan 30, 2020 at 22:20

2 Answers 2

2

$in should be fine for your case:

db.collection.find({ city: { $in: [ "Gotham City", "Central City" ] } })

Example

You can also use projection to get only hero names:

db.collection.find({ city: { $in: [ "Gotham City", "Central City" ] } }, { hero: 1 })

Example(2)

Sign up to request clarification or add additional context in comments.

3 Comments

OP asked for an 'AND' condition, you provided an 'OR' condition.
@barrypicker that's still unclear to me, lborghs, if me solution doesn't work for you please share an example with expected result, thanks both !
This solution works for me. In the meantime I also know why it didn't work for me before, because I tried this, but apparently I made a small error before this code ran. But anyhow, you got the right answer. Thanks!
0

This is what you're looking for.

db.collection.find({ city: { $in: [ "Star City", "Gotham City"] }},{ hero: 1, _id: 0 });

You can check this out for better undestanding. https://mongoplayground.net/p/ME7m_eupWzp

EDIT

Although i feel you were looking for an OR solution, in case if you were looking for an AND condition (where only heroes who were active in all the specified cities should be returned). But you'll need to modify your schema accordingly.

db.collection.find({
  city: {
    $all: [
      "Star City",
      "Central City",
      "Gotham City"
    ]
  }
},
{
  hero: 1,
  _id: 0
})

https://mongoplayground.net/p/39lBJuDIQDH.

1 Comment

OP asked for an 'AND' condition, you provided an 'OR' condition.

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.