MongoDB 检索数组中包含特定元素的所有行的查询
MongoDB query to Retrieve all the rows which contain a particular element inside an array
我是 MongoDb 的新手,我被困在这个查询中,
我想检索所有可用的小行
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"sizes":["small","medium","large"]
},
{
"_id":ObjectId("562e7c594c22942f08fe4193"),
"sizes":["small"]
},
{
"_id":ObjectId("562e7c594c12942f08fe4199"),
"sizes":["medium","large"]
},
我想要所有可用的小行,即
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"sizes":["small","medium","large"]
},
{
"_id":ObjectId("562e7c594c22942f08fe4193"),
"sizes":["small"]
},
我不知道您已经尝试过哪些命令,但是,也许可以尝试使用此命令:
myCursor = db.inventory.find( { 'sizes': "small" } )
因为这只会显示前 20 个文档,您可以放置一个循环:
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}
您需要使用 $elemMatch
xxx.find(
{ sizes: { $elemMatch: { $eq:"small" } } }
)
https://docs.mongodb.com/manual/reference/operator/query/elemMatch/
试试这个
db.sales.aggregate([
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: [ "$$item.sizes", small] }
}
}
}
}
}
])
或
db.users.find({sizes': "small"});
我是 MongoDb 的新手,我被困在这个查询中, 我想检索所有可用的小行
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"sizes":["small","medium","large"]
},
{
"_id":ObjectId("562e7c594c22942f08fe4193"),
"sizes":["small"]
},
{
"_id":ObjectId("562e7c594c12942f08fe4199"),
"sizes":["medium","large"]
},
我想要所有可用的小行,即
{
"_id":ObjectId("562e7c594c12942f08fe4192"),
"sizes":["small","medium","large"]
},
{
"_id":ObjectId("562e7c594c22942f08fe4193"),
"sizes":["small"]
},
我不知道您已经尝试过哪些命令,但是,也许可以尝试使用此命令:
myCursor = db.inventory.find( { 'sizes': "small" } )
因为这只会显示前 20 个文档,您可以放置一个循环:
while (myCursor.hasNext()) {
print(tojson(myCursor.next()));
}
您需要使用 $elemMatch
xxx.find(
{ sizes: { $elemMatch: { $eq:"small" } } }
)
https://docs.mongodb.com/manual/reference/operator/query/elemMatch/
试试这个
db.sales.aggregate([
{
$project: {
items: {
$filter: {
input: "$items",
as: "item",
cond: { $gte: [ "$$item.sizes", small] }
}
}
}
}
}
])
或
db.users.find({sizes': "small"});