Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在mongodb中查询嵌入式文档数组_Mongodb_Embedded Documents - Fatal编程技术网

在mongodb中查询嵌入式文档数组

在mongodb中查询嵌入式文档数组,mongodb,embedded-documents,Mongodb,Embedded Documents,我在编写需要将给定值与数组中所有嵌入文档中的某个字段进行比较的查询时遇到了一些问题。我将举一个例子,使这个问题不那么抽象 比如说,我想使用MongoDB存储我网络上的用户输入到不同在线搜索引擎的最后查询。集合中的条目将具有如下结构: { '_id' : 'zinfandel', 'last_search' : [ { 'engine' : 'google.com', 'query' : 'why is the sk

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

比如说,我想使用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在某个引擎中输入一个新的查询。将此查询存储在数据库中的代码需要找出用户使用的引擎是否已经存在条目。如果是,将使用新查询更新此条目。如果没有,则应创建一个新条目。我的想法是仅在给定引擎没有条目时执行
$push
,否则执行
$set
。为此,我试着这样写我的推送:

db.mycollection.update(
    { '_id' : username , search.$.engine : { '$ne' : engine } },
    { '$push' : { 'search.$.engine' : engine, 'search.$.query' : query } }
) 
但是,即使给定引擎已经有条目,也会推送一个新的嵌入文档。问题似乎是
$ne
操作符不能像我预期的那样处理数组。我需要的是一种方法,确保数组中没有一个嵌入的文档具有与指定引擎匹配的“引擎”条目


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

您可以使用以下命令将项目推入数组:

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

非常感谢你。我以前尝试过这个方法,但没有成功,可能是因为我在查询中使用了位置运算符
$。
。在您的示例中使用类似的
$nin
非常有效。