1

I am stuck at this. I'm trying to query two levels of nested documents with the index i.e [0]. Here's my mongoDb document.

[
  {
    "_id": ObjectId("5b8803a07078906483e2e8a9"),
    "vote": [
      [
        "a4d77175-250d-4990-bc1c-d79c8175c1f0",
        "5b82e2d1b47b3513f3f25854"
      ],
      [
        "a934cf1d-ecb1-4764-b8bb-9c3c40c1128d",
        "5b82e355b47b3513f3f25858"
      ]
    ],
    "election_id": ObjectId("5b82e3cfb47b3513f3f2585a"),
    "user_id": ObjectId("5b82e2d1b47b3513f3f25854"),
    "date": "Thu Aug 30 2018 17:48:00 GMT+0300 (EAT)",
    "__v": 0
  }
]

I'm trying to get to this value "a4d77175-250d-4990-bc1c-d79c8175c1f0" inside vote. I tried this to no avail.

exports.getVotesByPosts = (req, res, next) => {
  Vote.find({'vote[0][0]': req.params.id}, (err, vote) => {
    res.json(vote);
  }).sort( { date: -1 });
}

Thanks in advance for your help. Regards

1
  • do you know both the vote[0][0] and vote[0][1]? Commented Sep 8, 2018 at 13:52

2 Answers 2

1

You need to use $elemMatch query with the $eq operator

Vote.find({
  "vote": {
    "$elemMatch": {
      "$elemMatch": {
        "$eq": "a4d77175-250d-4990-bc1c-d79c8175c1f0"
      }
    }
  }
})
Sign up to request clarification or add additional context in comments.

6 Comments

can we use positional character $ in that to fetch only matched array?
$ is the projection operator we cannot use it to query.
yeah the question is can we use projection here
sir that's my question to you
Thanks Anthony Winzlet
|
0

Here's how i fixed it using Anthony's answer

    Vote.find({
      "vote": {
        "$elemMatch": {
          "$elemMatch": {
            "$eq": req.params.id
          }
        }
      }
    });

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.