1

I have these type of items on mongodb:

    {
    "_id": { "$oid" : "2" },
    "waypoints": [
        {
          "step": 0,
          "coordinates": [1,2]
        },
        {
          "step": 1,
          "coordinates": [1,3]
        },
        {
          "step": 2,
          "coordinates": [1,4]
        }
    ]
}

I tried to find [1,2] in the collection to retrieve waypoints.step and the _id, but the result is not what i expected.

I want to get:

{
    "_id": { "$oid" : "2" },
    "waypoints": [
        {
                "step": 0
        }
    ]
}

but i get:

{
    "_id": { "$oid" : "2" },
    "waypoints": [
        {
          "step": 0,
        },
        {
          "step": 1,
        },
        {
          "step": 2,
        }
    ]
}

what is the correct query to achieve what i want?

I know only the coordinates, i need to retrive _id of the object and the step corresponding to the coordinates I'm looking for.

thanks

2 Answers 2

1

You can do it by projecting data. The query should be :

db.collection.find({"_id": { "$oid" : "2" }},{waypoints : {$elemMatch : {coordinates:[1,2]}}})

For more information check $elemMatch operator.

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

2 Comments

I know only the coordinates, i need to retrive _id and the step corresponding to the coordinates I'm looking for
I have updated my answer. This query will return the _id and step that belongs to the given coordinates.
0

Because you're searching by coordinates, you can do it like this:

db.test.find({'waypoints.coordinates': [1,2]}, {'waypoints.$': 1})

In the projection, $ represents the index of the waypoints array where the coordinate was found.

You'll get the coordinates value along with the step, but that's the best you can do:

{
  "_id": "2",
  "waypoints": [
    {
      "step": 0,
      "coordinates": [
        1,
        2
      ]
    }
  ]
}

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.