1

I want to create a query in MongoDB to to find documents by and array of objects which exactly math document property.

I have documents:

{meta: {prop1: "hi1", prop2: "ho1"}},
{meta: {prop1: "hi2", prop2: "ho2"}},
{meta: {prop1: "hi3", prop2: "ho3"}},
{meta: {prop1: "hi1", prop2: "ho2"}}

I want to find documents whose meta property is one of exact objects in this array:

[
  {prop1: "hi1", prop2: "ho1"}, {prop1: "hi2", prop2: "ho2"}
]

Desired result would be documents:

{meta: {prop1: "hi1", prop2: "ho1"}},
{meta: {prop1: "hi2", prop2: "ho2"}}

but not:

{meta: {prop1: "hi1", prop2: "ho1"}},
{meta: {prop1: "hi2", prop2: "ho2"}},
{meta: {prop1: "hi1", prop2: "ho2"}}

2 Answers 2

1

Use $in operator.

Collection.find({
    meta:  { 
        $in: [
            { prop1: 'hi1', prop2: 'ho1'}, 
            { prop1: 'hi2', prop2: 'ho2'}
        ]
    } 
})
Sign up to request clarification or add additional context in comments.

Comments

0

We can Use $or for this -

Collection.find({
        $or: [
            {'meta.prop1': 'hi1', 'meta.prop2': 'ho1'},
            { 'meta.prop1': 'hi2', 'meta.prop2': 'ho2'}
        ]
})

Note: inside object of $or, $and condition is build.

We can use $in also because $in is inbuilt using $or.

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.