如何在Java Spring中使用MongoDB检查特定字段是否具有特定值?

huangapple go评论68阅读模式
英文:

How to check if specific field has specific value in MongoDB using Java Spring?

问题

这是我的结构。假设我在我的集合中有一堆这些对象。我想要搜索字段 twitterId 的值。在这种情况下,假设我想要检查是否在任何一个 twitterId 字段中存在 102030 的值?如何在Java Spring中构建这个查询?

Query query = new Query(Criteria.where("twitterId").is("102030"));
List<User> users = mongoTemplate.find(query, User.class);

其中,User 是你的数据对象类名,mongoTemplate 是 Spring Data MongoDB 提供的操作数据库的模板。

英文:

This is my structure. Let's say I have got a bunch of these objects in my collection. I want to search for value for the field twitterId. In this case, let's say I want to check whether 102030 value exists in any of my twitterId fields? How can I build this query in Java Spring?

{ 
&quot;_id&quot; : ObjectId(&quot;5f4edc8f0edc9e79dcd58cb4&quot;), 
&quot;twitterId&quot; : &quot;102030&quot;, 
&quot;fullName&quot; : &quot;Elon Musk&quot;, 
&quot;followers&quot; : [ ], 
&quot;_class&quot; : &quot;xxxx.yyyyy.model.User&quot; 
}

答案1

得分: 0

你需要一个用于进行搜索的存储库。创建类似这样的东西:

@Repository("user")
public interface UserRepository extends MongoRepository<User, String> {

    public Optional<User> findOneByTwitterId(String twitterId);

}

然后,你可以检查可选项中是否有值。

当然,还有很多其他解决方案。你还可以编写一个查询来计算有多少用户具有这个 Twitter ID。

英文:

You will need a repository which will do the search. Create something like this:

@Repository(&quot;user&quot;)
public interface UserRepository extends MongoRepository&lt;User, String&gt; {
	
	public Optional&lt;User&gt; findOneByTwitterId(String twitterId);

}

Then you can check if there is a value in the optional.

Of course they are plenty of other solution. You can also write a query to count how many users have this twitter id

答案2

得分: 0

@Repository("user")
public interface UserRepository extends MongoRepository<User, String> {
    @Query(value = "{'twitterId': ?0}", count = true)
    public int findByTwitterId(String twitterId);
}
英文:
@Repository(&quot;user&quot;)
public interface UserRepository extends MongoRepository&lt;User, String&gt; {
    @Query (value = &quot; {&#39;twitterId&#39;: ?0} &quot;, count = true)
    public int findByTwitterId(String twitterId);
}

huangapple
  • 本文由 发表于 2020年9月2日 20:16:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63705331.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定