The microbiota-gut-lung axis has elucidated a potential association between gut microbiota and idiopathic pulmonary fibrosis (IPF). However, there is a paucity of population-level studies with providing robust evidence for establishing causality. This two-sample Mendelian randomization (MR) analysis aimed to investigate the causal relationship between the gut microbiota and IPF as well as lung function. Adhering to Mendel's principle of inheritance, this MR analysis utilized summary-level data from respective genome-wide association studies (GWAS) involving 211 gut microbial taxa, IPF, and lung function indicators such as FEV1, FVC, and FEV1/FVC. A bidirectional two-sample MR design was employed, utilizing multiple MR analysis methods, including inverse variance-weighted (IVW), weighted median, MR-Egger, and weighted mode. Multivariable MR (MVMR) was used to uncover mediating factors connecting the exposure and outcome. Additionally, comprehensive sensitivity analyses were conducted to ensure the robustness of the results. The MR results confirmed four taxa were found causally associated with the risk of IPF. Order Bifidobacteriales (OR=0.773, 95% CI: 0.610-0.979, p=0.033), Family Bifidobacteriaceae (OR=0.773, 95% CI: 0.610-0.979, p=0.033), and Genus RuminococcaceaeUCG009 (OR=0.793, 95% CI: 0.652-0.965, p=0.020) exerted protective effects on IPF, while Genus Coprococcus2 (OR=1.349, 95% CI: 1.021-1.783, p=0.035) promote the development of IPF. Several taxa were causally associated with lung function, with those in Class Deltaproteobacteria, Order Desulfovibrionales, Family Desulfovibrionaceae, Class Verrucomicrobiae, Order Verrucomicrobiales and Family Verrucomicrobiaceae being the most prominent beneficial microbiota, while those in Family Lachnospiraceae, Genus Oscillospira, and Genus Parasutterella were associated with impaired lung function. As for the reverse analysis, MR results confirmed the effects of FEV1 and FVC on the increased abundance of six taxa (Phylum Actinobacteria, Class Actinobacteria, Order Bifidobacteriales, Family Bifidobacteriaceae, Genus Bifidobacterium, and Genus Ruminiclostridium9) with a boosted level of evidence. MVMR suggested monounsaturated fatty acids, total fatty acids, saturated fatty acids, and ratio of omega-6 fatty acids to total fatty acids as potential mediating factors in the genetic association between gut microbiota and IPF. The current study suggested the casual effects of the specific gut microbes on the risk of IPF and lung function. In turn, lung function also exerted a positive role in some gut microbes. A reasonable dietary intake of lipid substances has a certain protective effect against the occurrence and progression of IPF. This study provides novel insights into the potential role of gut microbiota in IPF and indicates a possible gut microbiota-mediated mechanism for the prevention of IPF.