Rytis Alekna
Rytis Alekna

Reputation: 1377

Find documents by an array of objects

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"}}

Upvotes: 1

Views: 48

Answers (2)

hardy
hardy

Reputation: 901

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.

Upvotes: 0

Mikey
Mikey

Reputation: 6766

Use $in operator.

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

Upvotes: 1

Related Questions