简体   繁体   English

Mongodb和Java:查找包含在数组字段中的具有指定值的文档

[英]Mongodb and Java: finding documents with a specified value contained in an array field

At the beginning I would like to highlight that however similar question was already asked, provided solution didn't solve my problem. 在一开始,我想强调一下,只要解决方案不能解决我的问题,就已经提出了类似的问题。 I'm new to Mongodb, hence I'm having the problem with it. 我是Mongodb的新手,因此遇到了问题。

What I want to do is writing a method for retrieving all shops from the collection called 'shopRepository' which "categories" field (that is an array of Strings) contains a category given as a method parameter. 我要写的是一种方法,用于从名为“ shopRepository”的集合中检索所有商店,其中“类别”字段(即字符串数组)包含作为方法参数给出的类别。

The document structure for the shopRepository collection is structured as follows: shopRepository集合的文档结构如下:

{
    "name": "corte",
    "openingHours": "Mi-Fr 8-18",
    "categories": ["food", "drinks"],
    "mallId": "123",
    "longitude": "1",
    "latitude": "2",
    "ownerId": "123x"
}

The method I have written looks like that: 我写的方法看起来像这样:

public List<Shop> getByCategory(String category) {

    BasicDBObject query = new BasicDBObject("categories", new BasicDBObject("$all", Arrays.asList(category)));
    List<Shop> shops = new ArrayList<Shop>();
    try (MongoCursor<Shop> cursor = collection.find(query).iterator()) {
        while (cursor.hasNext()) {
            shops.add(cursor.next());
        }
    }

    return shops;
}

When I call the method I'm getting HTTP Status 500 - java.lang.NullPointerException 当我调用该方法时,我的HTTP状态为500-java.lang.NullPointerException

Update: 更新:

This is stack trace: 这是堆栈跟踪:

SEVERE: Servlet.service() for servlet [Jersey REST Service] in context with path [/WebServiceProject] threw exception [java.lang.NullPointerException] with root cause java.lang.NullPointerException
at restLayer.ShopResource.getShopByCategory(ShopResource.java:114)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.glassfish.jersey.server.model.internal.ResourceMethodInvocationHandlerFactory.lambda$static$0(ResourceMethodInvocationHandlerFactory.java:76)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher$1.run(AbstractJavaResourceMethodDispatcher.java:148)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.invoke(AbstractJavaResourceMethodDispatcher.java:191)
at org.glassfish.jersey.server.model.internal.JavaResourceMethodDispatcherProvider$ResponseOutInvoker.doDispatch(JavaResourceMethodDispatcherProvider.java:200)
at org.glassfish.jersey.server.model.internal.AbstractJavaResourceMethodDispatcher.dispatch(AbstractJavaResourceMethodDispatcher.java:103)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.invoke(ResourceMethodInvoker.java:493)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:415)
at org.glassfish.jersey.server.model.ResourceMethodInvoker.apply(ResourceMethodInvoker.java:104)
at org.glassfish.jersey.server.ServerRuntime$1.run(ServerRuntime.java:277)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:272)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:268)
at org.glassfish.jersey.internal.Errors.process(Errors.java:316)
at org.glassfish.jersey.internal.Errors.process(Errors.java:298)
at org.glassfish.jersey.internal.Errors.process(Errors.java:268)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:289)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:256)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:703)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:416)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:370)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:389)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:342)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:229)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:506)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:962)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:445)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1115)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:637)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:318)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)

ShopResource.getShopByCategory is the method where I call 'getByCategory' method described above. ShopResource.getShopByCategory是我称之为上述“ getByCategory”方法的方法。 If it helps, I also include it: 如果有帮助,我也将其包括在内:

@GET
@Path("category/{category}")
@Produces({ MediaType.APPLICATION_JSON})
public Response getShopByCategory(@PathParam("category") String category) {
    List<Shop> shops = shopRepository.getByCategory(category);
    if (shops == null) {
        return Response.status(Status.NOT_FOUND).build();
    }
    List<Container> response = new ArrayList<Container>();
    for(Shop q : shops) {
        response.add((Container) stripAttributes(q));
    }
    return Response.ok(response).build();
}

Use the $in operator instead of $all like this: 使用$in运算符代替$all如下所示:

BasicDBObject query = new BasicDBObject("categories", new BasicDBObject("$in", Arrays.asList(category)));

$all means categories must contain all values specified in the query for the document to match. $all表示categories必须包含查询中指定的所有值,以便文档匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MongoDB / Java:根据值查找唯一文档 - MongoDB/Java: Finding unique documents based on value java mongodb 3.0:在内部文档数组中查找值 - java mongodb 3.0: find value in internal array of documents 使用java查找包含mongodb中特定值的数组的文档 - Find documents with array that contains a specific value in mongodb using java MongoDB:根据Java中另一个字段的值,使用新字段更新所有文档 - MongoDB: Update all documents with new field based on value of another field in java 如何使用Java从Mongodb中的子文档数组中仅获取所需字段 - How to get just the desired field from an array of sub documents in Mongodb using Java 如何获取文档,其中任何字段值都与MongoDB Java中列出的任何表达式匹配 - How to get documents, where any of the field value matches to any of the listed expressions in MongoDB Java 使用 Java 从 mongoDB 检索文档数组 - Retrieving an array of Documents from mongoDB with Java 使用Java查找矩阵中包含的最大整数值 - Finding the maximum integer value contained in a matrix using Java 如何使用Java驱动程序在MongoDB中更新数组的嵌入式文档中的字段值 - How to Update fields value in embedded documents of an Array in MongoDB using Java Driver 查询嵌套文档的数组以获得最高的字段值 - Query array of nested documents for highest value of field
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM