问题
We have a stocks collection:
stocks:
{"_id" : ObjectId("xxx"),"scrip" : "xxxxx2" }
{"_id" : ObjectId("xxy"),"scrip" : "xxxxx3" }
{"_id" : ObjectId("xyy"),"scrip" : "..." }
Given an input array of scrips [xxxxx7,xxxxx2,xxxxx3,xxxxx8]
,we need to return an array of the scrips not present in the stocks collection.
So the expected output is :
[xxxxx7,xxxxx8]
Is there a way to achieve this using Filter.expr and $setIsSubset(or any other alternative).
Not able to get an example of the same.
Help is appreciated
回答1:
You can achieve the expected result with MongoDB's Not In operator $nin and mapping the result to an array:
db.stocks.find({
"scripid": {"$nin": ["xxxxx7","xxxxx2","xxxxx3","xxxxx8"]}
}).toArray().map(stock => stock.scripid)
回答2:
Assuming data in collection :
stocks:
{"scripid" : "xxxxx2" }
{"scripid" : "xxxxx3" }
{"scripid" : "xxxxx4" }
So if you need to get the list of elements from Input Array which are not in scripid of stocks collection, but not the list of elements from stocks collection which are not in input array, then use this:
db.stocks.aggregate([ {
$group :{_id : null, scripids: {$push : '$scripid'}}
},{ "$project": { _id:0 , "inputArrayNINscripts": { "$setDifference": [ ['xxxxx7','xxxxx2','xxxxx3','xxxxx8'] , "$scripids" ] } } } ])
Output:
{
"inputArrayNINscripts" : [
"xxxxx7",
"xxxxx8"
]
}
Else if you need list of elements(scripid's) from stocks scripid which aren't in passed [xxxxx7,xxxxx2,xxxxx3,xxxxx8]
then, as suggested by @Caconde try this :
db.stocks.find({
"scripid": {"$nin": ["xxxxx7","xxxxx2","xxxxx3","xxxxx8"]}
}).toArray().map(scriptsNINArray => scriptsNINArray.scripid)
Output:
/* 1 */
[
"xxxxx4"
]
Add-ons:
As requested for java code, Please check these references:
mongoDB-java-driver Aggregation , SO link to java aggregation example
来源:https://stackoverflow.com/questions/57526020/present-in-input-array