不寻常的MongoDB查询

我需要做一个特殊的查询。 我有一个项目列表可用于做一些生产。 有了这个数据,我需要查询列表中的每种types的项目的文件。 几个(略)简单的文档看起来可能会这样。

{ "productname": "iron", "requirements": [ { "ammount": 2, "item": "coal" }, { "ammount": 2, "item": "ironore" } ], } { "productname": "coal", "requirements": [ { "ammount": 2, "item": "wood" } ], } { "productname": "copper", "requirements": [ { "ammount": 2, "item": "coal" }, { "ammount": 2, "item": "copperore" } ], } { "productname": "Chair", "requirements": [ { "ammount": 2, "item": "wood" }, { "ammount": 2, "item": "nails" }, { "ammount": 2, "item": "paint" } ], } { "productname": "Wooden Toy", "requirements": [ { "ammount": 2, "item": "wood" }, { "ammount": 2, "item": "paint" } ], } 

一个例子列表可能看起来像:[“木”,“啤酒”,“煤”,“油漆”,“铜矿”]

这应该返回“煤”,“铜”和“木制玩具”的文件,因此他们的所有要求都在列表中。 对于“主席”的“指甲”是失踪的,对于“铁”的“铁锅”丢失。

(对不起,我的英语不好 ;) )

您可以使用$redact $setIsSubset$setIsSubset作为$cond tion来执行此操作

 var myList = ["wood", "beer","coal", "paint", "copperore"] db.collection.aggregate([ { "$match": { "requirements.item": { "$in": myList } } }, { "$redact": { "$cond": [ { "$setIsSubset": [ "$requirements.item", myList ] }, "$$KEEP", "$$PRUNE" ] }} ]) 

从您提供的文件中,如果您想查找包含coalcoppercore requirements的文件,则可以使用以下查询:

 > db.materials.find({"requirements.item" : "coal", "requirements.item": "copperore" }).pretty() 

会返回:

 { "_id" : ObjectId("584990f083842cff8826d44f"), "productname" : "copper", "requirements" : [ { "ammount" : 2, "item" : "coal" }, { "ammount" : 2, "item" : "copperore" } ] } 

如果我正确地理解了你的问题(我不确定我是怎么做的),你可以使用all运算符:

 db.materials.find({"requirements.item": {$all: ["coal", "copperore"]}})