MongoDB 使用 Spring 启动时查询结果与预期不符
MongoDB query result not as expected using Spring Boot
我遇到了从 MongoDB 集合中获取数据的相关问题。
我在 MongoDB 数据库中有以下集合:
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
])
我有以下查询:
db.inventory.find( { dim_cm: { $gt: 25 } } )
结果:{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }
不过,我想要的结果应该是:
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 30 ] }
是否有可能得到上述结果。我尝试了不同的方法,但不幸的是我无法找到任何解决方案。
我们可以在aggregate
管道中使用$filter
来过滤数组
类似
db.collection.aggregate([
{
$match: { // to filter the documents
dim_cm: { $gt: 25 }
}
},
{
$project: {
_id: 1,
item: 1,
qty: 1,
tags: 1,
dim_cm: {
$filter: { // to filter the array
input: "$dim_cm",
as: "item",
cond: {
$gt: ["$$item", 25]
}
}
}
}
}
])
你可以在这里测试Mongo Playground
希望对您有所帮助
我遇到了从 MongoDB 集合中获取数据的相关问题。
我在 MongoDB 数据库中有以下集合:
db.inventory.insertMany([
{ item: "journal", qty: 25, tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
{ item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
])
我有以下查询:
db.inventory.find( { dim_cm: { $gt: 25 } } )
结果:{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] }
不过,我想要的结果应该是:
{ item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 30 ] }
是否有可能得到上述结果。我尝试了不同的方法,但不幸的是我无法找到任何解决方案。
我们可以在aggregate
管道中使用$filter
来过滤数组
类似
db.collection.aggregate([
{
$match: { // to filter the documents
dim_cm: { $gt: 25 }
}
},
{
$project: {
_id: 1,
item: 1,
qty: 1,
tags: 1,
dim_cm: {
$filter: { // to filter the array
input: "$dim_cm",
as: "item",
cond: {
$gt: ["$$item", 25]
}
}
}
}
}
])
你可以在这里测试Mongo Playground
希望对您有所帮助