I have a problem in MongoDB. I need to find all items where array only contains false key
My items looks like this
{
"field1" : "firstTest",
"field2" : [
{
"name" : "test1",
"use" : false
},
{
"name" : "test2",
"use" : true
},
{
"name" : "test3",
"use" : false
}
],
"updatedAt" : 2019-02-03T23:00:00.000 00:00
}
I need to match all items where field2 array only contains "use" key to false and "updatedAt" date is less than 3 years
I've start with something like :
await client.db(db).collection(collection).aggregate([{
$match:{
$and:[
{
field2: { $elemMatch: { use: { $all: [false] } }}
},
{
updatedAt: { $lt: moment().subtract(3,'years').toDate()}
}
]
}
}])
But it looks like my field2 query does not work
Do you have any idea how to match on boolean properties in array ?
Thanks in advance
CodePudding user response:
using $not
and $elemMatch
test it at mongoPlayground
await client.db(db).collection(collection).aggregate([
{
"$match": {
"$and": [
{
"field2": {
$not: {
$elemMatch: {
use: {
$ne: false
}
}
}
}
},
{
updatedAt: { $lt: moment().subtract(3,'years').toDate()}
}
]
}
}
])