MongoDB在数组字段中查找一个,每次都返回文档,即使没有匹配项

2024-06-09 18:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这样我就可以检查用户以前是否喜欢某个菜谱,这样他们就不会两次喜欢它了。 我的数据库中有如下用户:

username:"username"
password:"password"
likes:Array
0:"recipe_id"

我正在尝试使用查询:

 if mongo.db.users.find_one({'username': session.get('USERNAME')}, {'likes': [recipe_id]}) == None:
            mongo.db.recipe.update_one({'_id': ObjectId(recipe_id)}, {
                '$inc': {'likes': 1}})
            mongo.db.users.update_one({'username': session['USERNAME']}, {
                '$push': {'likes': recipe_id}})

但是它只是返回,不管recipeId是否在数组中。我想这是因为它做了两个查询。有没有办法指定第二个查询只查看该特定用户


Tags: 用户iddbsessionmongo检查用户usernamerecipe
1条回答
网友
1楼 · 发布于 2024-06-09 18:31:44

查询的问题是在.find_one的投影部分中有likes : [recipe_id]。所以它必须在过滤器部分,基本上第二个参数是投影,它有助于投影文档中的某些字段

尝试此查询:

/** So all you need is to check if `recipe_id` exists in `likes` array or not,
 * then if it exists instead of returning entire doc, 
 * using projection just return `_id` of doc which is quiet enough for your need,
 * in other case query will return none if no matching doc exists */

if mongo.db.users.find_one({'username': session.get('USERNAME'), 'likes': recipe_id}, {_id :1}) == None:
            mongo.db.recipe.update_one({'_id': ObjectId(recipe_id)}, {
                '$inc': {'likes': 1}})
            mongo.db.users.update_one({'username': session['USERNAME']}, {
                '$push': {'likes': recipe_id}})

.find_one()中,您不需要像正在做的那样将recipe_id包装到数组中:likes : [recipe_id]是不需要的,如果您想这样做,您需要在查询的过滤器部分使用像这样的$in操作符

参考:.findOne()&.find_one()

相关问题 更多 >