【问题标题】:Query an array of embedded documents in mongodb在 mongodb 中查询嵌入文档的数组
【发布时间】:2015-08-30 08:38:53
【问题描述】:

我在编写需要将给定值与数组中所有嵌入文档中的某个字段进行比较的查询时遇到了一些麻烦。我会举一个例子来让这个问题不那么抽象。

假设我想使用 MongoDB 来存储我网络上的用户输入不同在线搜索引擎的最后查询。集合中的条目将具有如下结构:

{
    '_id' : 'zinfandel', 
    'last_search' : [
        {
            'engine' : 'google.com',
            'query' : 'why is the sky blue' 
        },
        {
            'engine' : 'bing.com', 
            'query' : 'what is love'
        },
        {   'engine' : 'yahoo.com',
            'query' : 'how to tie a tie'
        }
    ]
}

现在假设用户 username 向某个 engine 输入一个新的查询。将此查询存储在数据库中的代码需要确定是否已经存在用户使用的引擎的条目。如果是,则该条目将使用新查询进行更新。如果没有,则应创建一个新条目。我的想法是只在给定引擎没有条目的情况下执行$push,否则执行$set。为此,我尝试这样写我的推送:

db.mycollection.update(
    { '_id' : username , search.$.engine : { '$ne' : engine } },
    { '$push' : { 'search.$.engine' : engine, 'search.$.query' : query } }
) 

但是,即使给定的引擎已经有一个条目,这也会推送一个新的嵌入文档。问题似乎是 $ne 运算符不能像我期望的那样与数组一起工作。我需要一种方法来确保数组中的不是单个嵌入文档具有与指定引擎匹配的“引擎”条目。

有人知道怎么做吗?请告诉我是否需要进一步澄清这个问题......

【问题讨论】:

    标签: mongodb embedded-documents


    【解决方案1】:

    您可以使用以下命令将项目推送到数组中:

    db.mycollection.update({
        _id: "zinfandel", 
        "last_search.engine": {
            $nin: ["notwellknownengine.com"]
        }
    }, {
        $push: {
            "last_search": {
                "engine" : "notwellknownengine.com", 
                "query" : "stackoveflow.com"
            }
        }
    });
    

    【讨论】:

    • 非常感谢。我之前尝试过,但没有成功,可能是因为我在查询中使用了位置运算符.$.。在您的示例中使用 $nin 就像一个魅力。
    猜你喜欢
    • 2021-08-07
    • 2015-02-06
    • 2021-03-24
    • 1970-01-01
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    相关资源
    最近更新 更多