如何对MongoDB使用聚合以基于

如何对MongoDB使用聚合以基于

本文介绍了如何对MongoDB使用聚合以基于$ and/$ or进行过滤?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太了解在MongoDB中使用$or$and运算符.

I don't quite understand to use $or or $and operators with MongoDB.

假设我有以下数据:

{
    "_id" : "0211dd50-6283-11e6-be4b-01259186ebdc",
    "customer_id" : 75832,
    "prod_display_id" : "8c890b9c-7824-11e5-9cf1-24519096eb0c",
    "record_ids" : [
        ObjectId("1377ki5f8782b634fbf92b07b"),
        ObjectId("6283gf5f922b634fbf32b07a"),
        ObjectId("9913zd5f234b634fbf22b07c")
    ],
    "create_dt" : ISODate("2014-01-12T13:31:42.740Z")
},
{
    "_id" : "3454ke24-9372-11e6-be4b-01259186ebdc",
    "customer_id" : 75832,
    "prod_display_id" : "2d723b5c-8823-77y5-9cf1-00259096eb0c",
    "record_ids" : [
        ObjectId("1377ki5f8782b634fbf92b07b")
    ],
    "create_dt" : ISODate("2014-03-12T15:45:01.650Z")
},
{
    "_id" : "0211dd50-6283-23t6-it84-63957834kjhdd",
    "customer_id" : 11486,
    "prod_display_id" : "8c890b9c-7824-11e5-9cf1-00259096eb0c",
    "record_ids" : [
        ObjectId("9870kr5f9234b745fbf23g12b")
    ],
    "create_dt" : ISODate("2015-02-23T16:23:53.112Z")
}
....

现在,我想查找所有具有特定record_id's的用户.假设我希望所有具有ObjectId(....)ObjectId(....)(即一个或另一个)的用户.

Now, I would like to find all of the users that have certain record_id's. Lets say I want all users that have ObjectId(....) OR ObjectId(....) (that is, one or the other.)

我认为正确的聚合运算符是:

I think the correct aggregation operator is:

> db.collection.aggregate([{ $project: { content_id : {$or : [ObjectId("...."), ObjectId("...")]}}}])

同样,AND运算应为

> db.collection.aggregate([{ $project: { content_id : {$and : [ObjectId("...."), ObjectId("...")]}}}])

但是我错了!如果我运行上述命令,则两个$project操作都会输出 all 文件,而不管是否存在某些ObjectId().我究竟做错了什么?

I am wrong however! If I run the above, both $project operations outputs all files, regardless whether the certain ObjectId() exists or not. What am I doing wrong?

推荐答案

首先,您不需要为此进行汇总;而且您不需要 $or 运算符.

First of all you don't need aggregation for this; and you don't need the $or operator.

要查找所有在"record_ids"中具有特定ObjectId的用户",只需使用 $in 运算符.

To find to find all "users" that have certain ObjectId in "record_ids" simply use the $in operator.

db.collection.find( { "record_ids": { "$all": <array of record_ids> } } )

要查找所有在"record_ids"中具有所有ObjectId的用户",只需使用 $all 运算符

To find to find all "users" that have all ObjectIds in "record_ids" simply use the $all operator

db.collection.find( { "record_ids": { "$in": <array of record_ids> } } )

这篇关于如何对MongoDB使用聚合以基于$ and/$ or进行过滤?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:07