Segev Lahav
Segev Lahav

Reputation: 47

How to write a mongo query that queries an array inside an object?

Lets say I have a mongo database that look like this:

[
  {
    dec: 5972,
    bin: [0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0]
  },
  {
    dec: 397250,
    bin: [1,1,0,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1,0]
  },
  {
    dec: 5,
    bin: [0,1,0,1]
  },
  {
    dec: 123,
    bin: [0,1,1,1,1,0,1,1]
  }
]

How do I query the database to give me all the objects that the number of '0' and '1' in their bin property is equal. For example, I would expect the result to be only:

{
  dec: 5,
  bin: [0,1,0,1]
}       

Upvotes: 2

Views: 84

Answers (1)

gmode
gmode

Reputation: 3740

Here you go:

db.test.aggregate([
{
    $project: {
        dec: "$dec",
        bin: "$bin",
        original_bin: "$bin"
    }
},

{
    $unwind: "$bin"
},
{
    $group: {
        _id: {
            dec: "$dec",
            bin: "$bin",
            original_bin: "$original_bin"
        },

        total: {
            $sum: 1
        }
    }
},
{
    $group: {
        _id: {dec: "$_id.dec", original_bin: "$_id.original_bin"},
        sums: {
            $addToSet: "$total"
        }
    }
},
{
    $match: {
        sums: {
            $size: 1
        }
    }
},
{
    $project: {
        _id: 0,
        dec: "$_id.dec",
        bin: "$_id.original_bin"
    }
}
]);

I have a sample data like this:

{"dec":1,bin: [0,0,0,1,0,1,1,1,0,1,0,1,0,1,0,0]}
{"dec":2,bin: [0,1,0,1,0,0]}
{"dec":3,bin: [1,0,1,0,1,0]}
{"dec":4,bin: [0,1,0,0]}
{"dec":5,bin: [0,0,0,1,1,1]}
{"dec":6,bin: [0,1]}

Given query on the sample data returns the desired arrays:

{ "dec" : 6, "bin" : [ 0, 1 ] }
{ "dec" : 3, "bin" : [ 1, 0, 1, 0, 1, 0 ] }
{ "dec" : 5, "bin" : [ 0, 0, 0, 1, 1, 1 ] }

Upvotes: 1

Related Questions