【问题标题】:Not able to write the query in mongo for array element match?无法在 mongodb 中编写查询以进行数组元素匹配?
【发布时间】:2016-01-28 13:04:47
【问题描述】:

我正在做一个项目,我必须为网站上的用户制作推荐系统。我是 Mongodb 的新手。 我想在下面的代码中检索具有“frnds.type”=1 的用户的名称/ID。

{
"_id" : ObjectId("56a9fcc15b4e12369150d6ef"),
"name" : "Udit",
"venue" : {
    "state" : "Rajasthan",
    "city" : "Jaipur",
    "ll" : [
        "26.9000",
        "75.8000"
    ]
},
"lsv" : [
    0.14,
    0.18,
    0.24,
    0.17,
    0.05,
    0.17,
    0.05
],
"username" : "udit",
"frnds" : [
    {
        "id" : "amit",
        "type" : 1
    },
    {
        "id" : "nakul",
        "type" : 0
    },
    {
        "id" : "verma",
        "type" : 1
    }
]

}

我已经写了一个查询,但是它给出了错误的结果

db.users.find({"username":"udit"},{"frnds":{"$elemMatch":{"type":1}}}).pretty()

我想要这样的结果:

[ { “身份证”:“阿米特”, “类型”:1 }, { “id”:“verma”, “类型”:1 } ]

【问题讨论】:

标签: arrays mongodb


【解决方案1】:

尝试使用Aggregation Framework,如下所示。

 db.users.aggregate([{
    $match: {username: 'udit'}, 
    {$unwind: '$frnds'}, 
    {$match: {'frnds.type': 1}}, 
    {$group: {frnds: {$push: "$frnds"}}
 }]);

【讨论】:

    猜你喜欢
    • 2018-04-04
    • 1970-01-01
    • 2021-05-06
    • 2023-03-04
    • 1970-01-01
    • 2013-08-10
    • 1970-01-01
    • 1970-01-01
    • 2013-11-12
    相关资源
    最近更新 更多