如何使用C#查询来自MongoDB的JSON数组返回的特定项目
我有一个从mongodb返回的json结果,每个元素旁边都有数组 我想查询数组元素以找到特定的节点, 而不使用ID或电子邮件作为过滤器仅将令牌号作为过滤器(其唯一号)
I have a json result return from mongodb each element has array onside it I would like to query the array element to find a specific node , without using the id or email as filter only the token number as a filter (its a unique number)
this is how one of the items json looks like
{
"_id" : ObjectId("5cf67ad97739bfe8525e5353"),
"Email" : "eyal@gmail.com",
"Username" : "eyal",
"Password" : "1234",
"Tokens" : [
{
"Tokennumber" : "123",
"Valid" : "true",
"LoginDate" : ISODate("2019-06-04T00:00:00.000Z")
},
{
"Tokennumber" : "124",
"Valid" : "false",
"LoginDate" : ISODate("2019-06-04T00:00:00.000Z")
},
{
"Tokennumber" : "555",
"Valid" : true,
"LoginDate" : ISODate("2019-06-07T08:32:01.854Z")
}
]
}
I would like to query the json using only one parameter Tokennumber=555
令牌号是唯一的,所以我需要通过他的令牌号查询来获取整个节点
the token number is a unique number so i need to fetch the whole node by querying it by his Tokennumber
the expected result would be the node
with this
data
"_id" : ObjectId("5cf67ad97739bfe8525e5353"),
"Email" : "eyal@gmail.com",
"Username" : "eyal",
"Password" : "1234",
以下mongo查询使用$ elemMatch完成工作
the following mongo query get's the job done using $elemMatch
db.User.aggregate({
"$match": {
"Tokens": {
"$elemMatch": {
"TokenNumber": "234"
}
}
}
})
这是生成上述聚合管道的c#代码.它使用的是 MongoDB.Entities ,它只是官方驱动程序的包装. [免责声明:我是作者]
here's the c# code that generated the above aggregation pipeline. it's using MongoDB.Entities which is just a wrapper for the official driver. [disclaimer: i'm the author]
using MongoDB.Entities;
using System.Linq;
namespace StackOverflow
{
public class Program
{
public class User : Entity
{
public string Email { get; set; }
public Token[] Tokens { get; set; }
}
public class Token
{
public string TokenNumber { get; set; }
public bool Valid { get; set; }
}
static void Main(string[] args)
{
new DB("test");
(new User
{
Email = "email@domain.com",
Tokens = new[] {
new Token{ TokenNumber="123",Valid = false },
new Token{ TokenNumber="234",Valid = true },
new Token{ TokenNumber="456",Valid = false },
}
}).Save();
var user = DB.Queryable<User>()
.Where(u => u.Tokens.Any(t => t.TokenNumber == "234"))
.Single();
}
}
}
由于您提到无法使用该库,因此以下是使用官方驱动程序的方法:
since you mentioned you are unable to use the library, the following would be how to do it with the official driver:
var filter = Builders<User>.Filter
.ElemMatch(u => u.Tokens,
t => t.TokenNumber == "234");
var user = collection.Find(filter)
.Single();
var user = collection.Aggregate()
.Match(u => u.Tokens.Any(t => t.TokenNumber == "234"))
.ToList()
.Single();
var user = collection.AsQueryable()
.Where(u => u.Tokens.Any(t => t.TokenNumber == "234"))
.Single();