给出以下示例,我想查询包含两个文档({x:30,y:40} {x:40,y:50},与“时间”无关)的_id。但是x和y需要过滤。
{
"_id" : ObjectId("5caa04c6eef934095e66ebc5"),
"position" : [
{
"x" : 30,
"y" : 40,
"time" : ISODate("2019-03-28T14:00:00Z")
},
{
"x" : 40,
"y" : 50,
"time" : ISODate("2019-03-28T14:00:00Z")
},
{
"x" : 50,
"y" : 60,
"time" : ISODate("2019-03-28T14:00:00Z")
}
]
}
例如(无效):
db.testes.find({position: {$all: [{x:{$gt:28,$lte:32}, y:{$gt:38,$lte:42}, time:{$gte: ISODate("2019-03-28T14:00:00Z")}}, {x:{$gt:38,$lte:42}, y:{$gt:48,$lte:52}, time: {$gte: ISODate("2019-03-28T14:00:00Z")}}]}})
或
db.testes.find({position: {$all: [{x:{$gt:28,$lte:32}, y:{$gt:38,$lte:42}}, {x:{$gt:38,$lte:42}, y:{$gt:48,$lte:52}}]}})
但这可行:
db.testes.find({position: {$all: [{x:30, y:40, time:ISODate("2019-03-28T14:00:00Z")}, {x:40, y:50, time:ISODate("2019-03-28T14:00:00Z")}]}})
感谢您的帮助
答案 0 :(得分:0)
请尝试这个
$ helm version
Client: &version.Version{SemVer:"v2.13.1", GitCommit:"618447cbf203d147601b4b9bd7f8c37a5d39fbb4", GitTreeState:"clean"}
Server: &version.Version{SemVer:"v2.13.1", GitCommit:"618447cbf203d147601b4b9bd7f8c37a5d39fbb4", GitTreeState:"clean"}
答案 1 :(得分:0)
您可以通过$project($filter)在MongoDb aggregation内过滤子文档数组。尝试如下操作:
db.collection.aggregate([
{
$project: {
position: {
$filter: {
input: "$position",
as: "pos",
cond: {
$or: [
{ $and: [ { $eq: [ "$$pos.x", 30 ] }, { $eq: [ "$$pos.y", 40 ] } ] },
{ $and: [ { $eq: [ "$$pos.x", 40 ] }, { $eq: [ "$$pos.x", 50 ] } ] }
]
}
}
}
}
}
])
您将获得的结果如下:
{
"_id" : ObjectId("5caa04c6eef934095e66ebc5"),
"position" : [
{
"x" : 30,
"y" : 40,
"time" : ISODate("2019-03-28T19:30:00.000+05:30")
}
]
}