我在编写一个查询时遇到了一些困难,这个查询需要将给定的值与数组中所有嵌入文档中的某个字段进行比较。我将举一个例子,使这个问题不那么抽象。
假设我想使用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'
}
]
}现在假设用户用户名在某个引擎中输入一个新的查询。在DB中存储此查询的代码需要确定用户使用的引擎是否已经存在一个条目。如果是,则使用新查询更新此条目。如果没有,则应该创建一个新条目。我的想法是,只有在没有给定引擎的条目的情况下才执行$push,否则执行$set。为此,我试图这样写我的推:
db.mycollection.update(
{ '_id' : username , search.$.engine : { '$ne' : engine } },
{ '$push' : { 'search.$.engine' : engine, 'search.$.query' : query } }
) 但是,即使已经有给定引擎的条目,这也会推动一个新的嵌入式文档。问题似乎是,$ne操作符不能像我期望的那样处理数组。我需要一种方法来确保--数组中没有一个嵌入文档--有一个与指定引擎匹配的“引擎”条目。
有人知道怎么做吗?如果我需要进一步澄清这个问题..。
发布于 2015-06-14 23:36:44
可以使用以下命令将项推入数组中:
db.mycollection.update({
_id: "zinfandel",
"last_search.engine": {
$nin: ["notwellknownengine.com"]
}
}, {
$push: {
"last_search": {
"engine" : "notwellknownengine.com",
"query" : "stackoveflow.com"
}
}
});https://stackoverflow.com/questions/30835201
复制相似问题