1

I have s schema like:

var EntitySchema = new Schema({
  name : {type: String, default: null},
  organizations : [{
    id: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'Organization'
    }}]
});

I have an id of organization, How can I make a query for Entity.find({}) and find Entity that has this id in its organizations array?

I used this in mongo shell

db.entity.find({"organizations.id": { $in: [ObjectId("ididididididid")]}}).pretty()

and it worked, but it doesn't work in express method, do I do something wrong? Does $in works both ways? I have a feeling that its not what I should be using in this query.

2
  • What your data looks like? organization: [ { id: ObjectId('hashedvalue44') } ] Commented Nov 19, 2019 at 12:36
  • organizations: [{id: 'hashedvalue44'}, {id: 'hashedvalue55'}], or organizations: ['hashedvalue44', 'hashedvalue55'] either is acceptable as of now. Commented Nov 19, 2019 at 14:31

1 Answer 1

1

As per mongo documentation, you can query as below

db.entity.find({ "organizations" : { $elemMatch: { "id" : ObjectId("ididididididid") } }}).pretty();

Ref: https://docs.mongodb.com/manual/tutorial/query-array-of-documents/

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

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.