0

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

2
  • You could try db.stocks.find({ '$expr': { '$not': { '$in: [ "$scripid" , inputArray ] } } }).toArray().map(doc => doc.scripid)? Commented Aug 16, 2019 at 14:11
  • Thanks.But what is the equivalent using java driver aggregate.We are using driver 3.5+ Commented Aug 16, 2019 at 16:11

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Could not find the setDifference function for java driver though
@IUnknown : not sure about java driver, but does the query work in DB ? Please put on a tag for JAVA or raise a new question, meanwhile just found something here in SO, Please check this for java : stackoverflow.com/questions/42351139/…
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.