问题
I don't quite understand to use $or
or $and
operators with MongoDB.
Let's say I have following data:
{
"_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")
}
....
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("...")]}}}])
Similarly, the AND operation should be
> db.collection.aggregate([{ $project: { content_id : {$and : [ObjectId("...."), 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?
回答1:
First of all you don't need aggregation for this; and you don't need the $or operator.
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> } } )
To find to find all "users" that have all ObjectId
s in "record_ids" simply use the $all operator
db.collection.find( { "record_ids": { "$in": <array of record_ids> } } )
回答2:
You don't require any aggregate to run such simple queries.
db.collection.find({$or : [{"content_id":ObjectId("....")},{"content_id": ObjectId("...")} ] } )
OR
db.collection.find({"content_id":{ "$in":[ObjectId("...."),ObjectId("....")] } } )
https://docs.mongodb.org/v3.0/reference/operator/query/in/
来源:https://stackoverflow.com/questions/35019119/how-to-use-aggregation-for-mongodb-to-filter-based-on-and-or