如何在Mongo文档中查询字典?

3

我有一个文件,如下所示

这是我用C#为该文件设计的结构

public class MetaData
{
  [BsonId]
  public ObjectId _Id { get; set; }
  [BsonElement("User")]
  public IDictionary<Int64, FirstUser> User { get; set; }
}

public class FirstUser
{
    [BsonElement("Name")]
    public String Name { get; set; }
    [BsonElement("Id")]
    public Int64 Id { get; set; }
}

这是我为该文档设计的 BSON 结构。
/* 1 */
{
    "_id" : ObjectId("5805c1ced520b54bd4192214"),
    "User" : [ 
        [ 
            NumberLong(1), 
            {
                "Name" : "FirstUser",
                "_id" : NumberLong(1)
            }
        ]
    ]
}

/* 2 */
{
    "_id" : ObjectId("5805c1ced520b54bd4192215"),
    "User" : [ 
        [ 
            NumberLong(1), 
            {
                "Name" : "SecondUser",
                "_id" : NumberLong(2)
            }
        ]
    ]
}


/* 3 */
{
    "_id" : ObjectId("5805c1ced520b54bd4192216"),
    "User" : [ 
        [ 
            NumberLong(1), 
            {
                "Name" : "ThirdUser",
                "_id" : NumberLong(3)
            }
        ]
    ]
}


/* 4 */
{
    "_id" : ObjectId("5805c1ced520b54bd4192217"),
    "User" : [ 
        [ 
            NumberLong(1), 
            {
                "Name" : "FourthUser",
                "_id" : NumberLong(2)
            }
        ]
    ]
}

我需要所有名称为“FirstUser”的文档,我应该如何构建MONGO查询?

您的BSON模式和类似乎不匹配... 您的BSON似乎将“User”作为对象数组的数组,而不仅仅是字典。 - Felipe Sabino
我可以建议您使用聚合框架来解决这个问题吗?如果可以,我可以为您撰写答案。 - Daniele Tassone
我已经尝试过它是有效的,但问题在于我无法获取超过16 MB的数据。有时我需要获取超过16 MB的数据。 - Gopinath Navaneethan
3个回答

2
这里的问题在于你的字典键是数字。通常你会使用类似于 "User.1.Name": "FirstUser" 的语法,但这种语法实际上会做另一件事情:在 User 中查找第二个元素,该元素具有 Name=FirstUser(因为索引是从零开始的)。
如果你在 User 中只有一个键,那么可以使用 "User.0.Name": "FirstUser"

这个可以运行,但问题在于用户可能来自任何地方,我们无法确定它是否总是排在字典的第一位。 - Gopinath Navaneethan
你能举个例子说明什么情况下会用到你的模式吗? - Tomer

1

您可以使用以下命令在mongo shell中执行:

db.collection.find({'User.Name': 'FirstUser'});

或者从C#驱动程序中,您可以执行以下操作:

var c = await wat.FindAsync(x => x.User[0].Name == "FirstUser");
var metaData = await c.ToListAsync();

实际上我需要Mongo查询,因为我首先要进行查询,然后再尝试获取文档。如何为此进行制作? - Gopinath Navaneethan

0
Here is on example that works for me:

`var query = new Dictionary<string, object>()`
            {
                { "$match", new { id = 11 }}
             };`

 
var result = services.Query<objectType>(query);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接