Mongodb 我想检索与查询匹配的子文档
请参阅以下文件Mongodb 我想检索与查询匹配的子文档,mongodb,Mongodb,请参阅以下文件 { "_id" : ObjectId("594b9eb9e1b22e09f8af00ee"), "Name" : "Master List", "UserId" : ObjectId("594b9eb9e1b22e09f8af00ed"), "Items" : [ { "_id" : ObjectId("59485d9d0fd04d1294e06766"), "Title" : "M
{
"_id" : ObjectId("594b9eb9e1b22e09f8af00ee"),
"Name" : "Master List",
"UserId" : ObjectId("594b9eb9e1b22e09f8af00ed"),
"Items" : [
{
"_id" : ObjectId("59485d9d0fd04d1294e06766"),
"Title" : "Muscle Milk Protein",
},
{
"_id" : ObjectId("59485d9d0fd04d1294e06772"),
"Title" : "Baby Macro Organic 120g",
},
{
"_id" : ObjectId("59485d9d0fd04d1294e06780"),
"Title" : "Fruit Bread Soft Strap",
}
]
}
从上面的文档中,我想要基于搜索字符串的结果,例如:“/.Mus./”我应该得到以下结果,但我得到的是如上所述的整个项目的详细信息
{
"_id" : ObjectId("594b9eb9e1b22e09f8af00ee"),
"Name" : "Master List",
"UserId" : ObjectId("594b9eb9e1b22e09f8af00ed"),
"Items" : [
{
"_id" : ObjectId("59485d9d0fd04d1294e06766"),
"Title" : "Muscle Milk Protein",
}
]
}
我尝试了以下查询,但没有一个从Items子文档中获取匹配的标题
Query1:db.getCollection('List').find({'UserId':新ObjectId(“594b9eb9e1b22e09f8af00ed”),'Items':{'elemMatch':{'Title':{$regex:'.*uscle.*}}}
Query2:db.getCollection('List').find({'UserId':新ObjectId(“594b9eb9e1b22e09f8af00ed”),'Items.Title':{$regex:'.*Mus.*}})
你能帮忙吗
提前感谢。使用“解包”嵌套数组
db.getCollection.aggregate([
{
$unwind:"$Items"
},
{
$match: {
"Items.title": {
regex: /yourPattern/
}
}
}
])
希望有帮助!聚合在MongoDB中真是太棒了。在find()中是否有机会容纳相同的逻辑?恐怕没有。是否有使用“查找”的原因?没有具体原因。我只是想知道使用find()是否可以实现这一点,如果可以,请提供帮助?我试着按照我的需求查询模式,似乎工作得很好。聚合({$unwind:“$Items”},{$match:{“Items.Title:{$regex:'.*Mus.*'}},{$match:{“UserId”:新ObjectId(“594b9eb9e1b22e09f8af00ed”)})很高兴看到$unwind
正在为您工作。我不知道如何使用find()
,或者使用forEach()
,获得相同的结果,但我只是在讨论。至于您的查询,您可以使用$和与$match
:db.getCollection('List').aggregate([{$unwind:$Items“},{$match:{$and:[{”Items.Title:{$regex:'.*Mus.'},{“UserId”:newobjectid(“594B9EB9E1B22E09AFF800ED”)}})一起使用({$match:{$and:[{”Items.Title:{$regex:'.'.*.'.},{'Mus.'},{“UserId:”newobjectid:“}])