如何获取数组不包含"apple"元素的文档,但如果它包含除 apple 以外的其他元素,那么它应该返回文档



让我举个例子。有一个收集车辆列表(

{
"driver" : 1,

"driver_vehicles" : [ 
{
"name" : "Car1",
"state" : 1
"vehicledates" : []
}, 
{
"name" : "Car2",
"vehicledates" : [ 
{
"trip" : ObjectId("6374c5521e0056579430e15e"),
"trip_date" : "Nov 28, 2022"
}, 
{
"trip" : ObjectId("6374c3c65c106e84520e2bda"),
"trip_date" : "Nov 30, 2022"
}, 
{
"trip" : ObjectId("63789e73aab4b1b08dac4d23"),
"trip_date" : "Dec 1, 2022"
}
],
"state" : 1
}, 
{
"name" : "Car3"
"vehicledates" : [ 
{
"trip_id" : ObjectId("63776d5b9061c736099501ac"),
"trip_date" : "Dec 2, 2022"
}
],
"state" : 1
}
],
}

)'

我想要的是让司机没有一辆在Dec 1, 2022state:1上都没有行程的车辆所以我做了一个查询

db.vehicle_list.find({"driver_vehicles.vehicledates.trip_date": {$nin: ["Dec 1, 2022"]},"state":1})

不返回_id 1文档

现在我明白car2Dec 1, 2022,所以它不应该返回。但是Car1Car3没有Dec 1, 2022,它也匹配条件state:1,所以它应该返回文档。希望你明白我的意思。如果你有任何疑问,请告诉我。

I tried this query

db.vehicle_list.find({"driver_vehicles.vehicledates.trip_date": {$nin: ["Dec 1, 2022"]},"state":1})

这不会返回文档_id 1但是它没有返回Driver 1

相反,我认为$elemMatch操作符将按照您的需要工作。

db.collection.find({
"driver_vehicles": {
$elemMatch: {
"vehicledates.trip_date": {
$nin: [
"Dec 1, 2022"
]
},
"state": 1
}
}
})

Demo @ Mongo Playground

最新更新