存在于输入数组中 [英] Present in input array

查看:86
本文介绍了存在于输入数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个库存集合:

stocks:

{"_id" : ObjectId("xxx"),"scrip" : "xxxxx2" }
{"_id" : ObjectId("xxy"),"scrip" : "xxxxx3" }
{"_id" : ObjectId("xyy"),"scrip" : "..." }

给出一个价目表<$的输入数组c $ c> [xxxxx7,xxxxx2,xxxxx3,xxxxx8] ,我们需要返回一个不在股票集合中的股票的数组。

因此,预期输出为:

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]

有没有一种方法可以使用Filter.expr和$ setIsSubset(或任何其他替代方法)来实现。

无法获得相同的示例。

感谢您的帮助

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

推荐答案

假定集合中的数据为:

股票:

{"scripid" : "xxxxx2" }
{"scripid" : "xxxxx3" }
{"scripid" : "xxxxx4" }

您需要获取元素列表来自输入数组的元素,而不位于股票集合的 scripid 中,但不在输入集合中的股票集合的元素列表中,则使用以下命令:

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" ] } } } ])

输出:

{
    "inputArrayNINscripts" : [ 
        "xxxxx7", 
        "xxxxx8"
    ]
}

否则,如果您需要股票 scripid元素列表(scripid) 未被传入的 [xxxxx7,xxxxx2,xxxxx3,xxxxx8] ,然后按照@Caconde的建议尝试以下操作:

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)

输出:

/* 1 */
[
    "xxxxx4"
]

附加组件:

请输入Java代码,请检查这些引用:

As requested for java code, Please check these references:

mongoDB-java驱动程序聚合 SO链接至java聚合示例

这篇关于存在于输入数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆