Python 带有$或嵌套子句的Mongodb聚合
我有如下mongodb文档:Python 带有$或嵌套子句的Mongodb聚合,python,mongodb,Python,Mongodb,我有如下mongodb文档: { "_id" : ObjectId("5d35ba501545d248c383871f"), "key1" : 1, "currentTime" : ISODate("2019-07-18T19:41:54.000Z"), "iState" : "START - 1", "errGyro" : -4.0, "states" : [ { "ts" : 3,
{
"_id" : ObjectId("5d35ba501545d248c383871f"),
"key1" : 1,
"currentTime" : ISODate("2019-07-18T19:41:54.000Z"),
"iState" : "START - 1",
"errGyro" : -4.0,
"states" : [
{
"ts" : 3,
"accY" : -165.877227783203,
"gyroZ" : 8.2994499206543,
},
{
"ts" : 4,
"accY" : -15.843573,
"gyroZ" : 12.434643,
},
{
"ts" : 3,
"accY" : 121.32667,
"gyroZ" : 98.45566,
}
]
}
我想返回所有states对象和父文档,其中“ts”是3或5
我首先尝试了这个查询:
db.getCollection('logs').find(
{"states" :
{ "$elemMatch" : { "$or":[
{ "ts":
{ "$eq" : 3}
},
{ "ts":
{ "$eq" : 5}
}
]
}
}
},{"states.$":1 })
但这只返回发生“eq”的第一个“state”文档。
如何归还所有匹配的文档?
谢谢。由于$elemMatch只返回数组的第一个匹配元素,因此必须使用聚合来实现目标。问题是:
db.collection.aggregate([
{
$match: {
$or: [
{
"states.ts": {
$eq: 3
}
},
{
"states.ts": {
$eq: 5
}
}
]
}
},
{
$project: {
states: 1
}
},
{
$unwind: "$states"
},
{
$match: {
$or: [
{
"states.ts": {
$eq: 3
}
},
{
"states.ts": {
$eq: 5
}
}
]
}
},
{
$group: {
_id: "$_id",
states: {
$push: "$states"
}
}
}
])
如果返回了许多文档,那么这里的第一个$match和$project阶段用于查询优化和内存节省。您可以使用聚合管道
db.getCollection('logs').aggregate([
{
$unwind: "$states"
},
{
$match: {
$or: [
{ "states.ts": 3 },
{ "states.ts": 5 },
]
}
},
{
$group: {
_id: "$_id",
"key1": { $first: "key1" },
"currentTime": { $first: "currentTime" },
"iState": { $first: "$iState" },
"errGyro": { $first: "$errGyro" },
states: { $push: "$states" }
}
}
])
尝试从项目参数{“状态”:1}中删除
$