微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

从mongodb集合中的数组获取价值

如何解决从mongodb集合中的数组获取价值

collection:
{    
    "username" : "gorim99949@x1post.com","channels" : [ 
        {
            "channelName" : "yyyyy","id" : 383,"url" : "https://xxxxxxxxx",}
    ],}

@Document(collection = "user_masters")
public class UserMasters {
  @Field("username")
  private String userName;

  @DBRef
  private List<UserChannels> UserChannels userChannels;
   ******getter and setter*********

@Document(collection="channels")
public class UserChannels {
  private String url;
 ************getter/setter****************


Repository class
public UserMasters  findByUserName(String username);

@Test method
Query: userRepository.findByUserName(userName).getUserChannels().getUrl();

我如何从mongodb中的集合中的数组获取url的值。我无法读取集合中数组中的值。预先感谢您的帮助

解决方法

您将需要一个自定义查询来执行此操作。 运行此查询: db.collection.aggregate({$ match:{username:“ gorim99949@x1post.com”}},{$ project:{“ userChannels”:“ $ channels.url”}})); 它将返回: [{“ _id”:ObjectId(“ 5a934e000102030405000000”),“ userChannels”:[“ https:// xxxxxxxxx”]}]。 您可以通过将投影中的_id设置为0来从返回的文档中删除_id。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。