简体   繁体   English

如何在 Java 中运行 MongoDB 查询

[英]How to run a MongoDB query in Java

I have queries copied from the MongoDB tutorial, but they are not recognized in IntelliJ.我有从 MongoDB 教程中复制的查询,但它们在 IntelliJ 中无法识别。 Is it because the driver is version 1.8.2?是不是因为驱动是1.8.2版本? I can't figure out how to update this to a newer version.我不知道如何将其更新到较新的版本。

I've taken the example query shown below from https://mongodb.github.io/mongo-java-driver/4.1/driver/getting-started/quick-start/我从https://mongodb.github.io/mongo-java-driver/4.1/driver/getting-started/quick-start/获取了下面显示的示例查询

However, intellij tells me that it cannot resolve the method eq.但是,intellij 告诉我它无法解析方法 eq。

myDoc = collection.find(eq("i", 71)).first();
System.out.println(myDoc.toJson());

Or this query.或者这个查询。 IntilliJ will tell me that the colon is an unexpected token IntilliJ 会告诉我冒号是一个意外的标记

db.inventory.find( { status: { $in: [ "A", "D" ] } } )

在此处输入图片说明

I suspect you are missing the static import.我怀疑您错过了静态导入。

import static com.mongodb.client.model.Filters.eq;

Try adding this.尝试添加这个。 It will not throw compilation error.它不会抛出编译错误。 Please check the import statement against the version of java driver.请根据 java 驱动程序的版本检查导入语句。

However, intellij tells me that it cannot resolve the method eq.但是,intellij 告诉我它无法解析方法 eq。

Did you added the MongoDB dependency to Maven?您是否将 MongoDB 依赖项添加到 Maven?

<dependencies>
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongodb-driver-sync</artifactId>
    <version>4.1.1</version>
</dependency>

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM