Valeri
Valeri

Reputation: 73

How do I get only the documents that dont have 'false' in an array of boolean values?

Suppose I have these documents:

[
    {
        _id: 132143124,
        orders: [true, false, false],
    },
    {
        _id: 3123,
        orders: [true, true, true],
    },
];

How do I get only the documents that dont have 'false' in their orders array. I need an aggregate stage solution. ( MongoDB aggregate solution )

Upvotes: 1

Views: 43

Answers (2)

elsybilo
elsybilo

Reputation: 56

You could use filter function for arrays:

const results = [
  {
    _id: 1,
    orders: [true, false, false],
  }, {
    _id: 2,
    orders: [true, true, true],
  }
]
    
const filtered_results = results.map(({orders, ...data}) => {
  return {
    orders: orders.filter((order)=>order === true), 
    ...data
  }
})
    
console.log(filtered_results)

Upvotes: 0

Tom Slabbaert
Tom Slabbaert

Reputation: 22296

You can use $not or $ne ( as Mongo's query language flattens arrays ) for this, like so:

db.collection.find({
  orders: {$ne: false}
})

Mongo Playground

same syntax will work in the aggregation pipeline: Mongo Playground Aggregation

Upvotes: 2

Related Questions