3

I have a Document, shown below

This is my C# structure for that document

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; }
}

This is my BSON structure for that document

/* 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)
            }
        ]
    ]
}

I need all documents which are having "Name" as "FirstUser", For this how do I form MONGO QUERY?

2 Answers2

1

The problem here is that your dictionary keys are numbers. Usually you'd use something like "User.1.Name": "FirstUser", but this syntax actually does something else: looking for the second element in User which has Name=FirstUser (because the indexing is zero-based).

If you have only one key in User, you can use "User.0.Name": "FirstUser".

Tomer
  • 1,376
  • 9
  • 18
1

You can do it from the mongo shell using the following:

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

Or from the c# driver you can do the following:

var c = await wat.FindAsync(x => x.User[0].Name == "FirstUser");
var metaData = await c.ToListAsync();
Kevin Smith
  • 10,855
  • 1
  • 33
  • 59